How to use MapRoute with Areas in MVC3

andy picture andy · Jul 22, 2012 · Viewed 10k times · Source

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?

Answer

Ecnalyr picture Ecnalyr · Jul 22, 2012

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.