How to use MapRoute with Areas in MVC3

10,150

Solution 1

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.

Solution 2

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.

Share:
10,150
andy
Author by

andy

dad, photographer, software engineer. thatandyrose.com

Updated on June 04, 2022

Comments

  • andy
    andy almost 2 years

    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?