andy
andy

Reputation: 8875

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?

Upvotes: 3

Views: 11099

Answers (2)

andy
andy

Reputation: 8875

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.

Upvotes: 5

Ecnalyr
Ecnalyr

Reputation: 5802

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.

Upvotes: 5

Related Questions