简体   繁体   中英

How to use MapRoute with Areas in MVC3

I've got an Area in my web app called "Admin".

So, http://localhost.com/Admin goes to the Home Controller and Index Action in the Admin Area.

However, I want to be able to hit the Admin Home Controller and Index Action with the following Url:

http://localhost.com/Hello

I've got this as my attempt:

routes.MapRoute(
            "HelloPage",
            "Hello/{controller}/{action}",
            new{area= "Admin", controller = "Home", action = "Index"},
            new[] { typeof(Areas.Admin.Controllers.HomeController).Namespace });

As you can see I'm specifying the namespace and the area, but all I get is the routing error:

The view 'Index' or its master was not found or no view engine supports the searched locations.

It's not searching in the Admin area.

Any ideas?

Try this:

routes.MapRoute(
       "HelloPage",
       "Hello/{controller}/{action}/{id}",
       new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

And then add this to your Admin controller action:

  if (!this.ControllerContext.RouteData.DataTokens.ContainsKey("area"))
  {
      this.ControllerContext.RouteData.DataTokens.Add("area", "Admin")
  }

You can check here for further documentation.

The problem was that I was setting the route in Global.asax.

I should have been setting it in the AreaRegistration in the Admin area. Once I did that the problem was fixed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM