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?

Answers


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.


Need Your Help

asp.net client developed with 4.0 SDK schould be converted in 2011 SDK (with support of Dynamics 4.0)

dynamics-crm dynamics-crm-2011 crm dynamics-crm-4 microsoft-dynamics

I have developed an asp client with 4.0 SDK. To work with Dynamics 2011 I use 2007 endpoints (they are there for backward compatibility). But since last month is only "Office 365" authetification

How to only affect 1 gameobject in an if statement

c# if-statement unity3d fsm

Making an AI game, trying to only affect 1 gameobject in an if statement. I think the way I'm doing it is very wrong, and I was advised to create an array of my instance of my enum. I'm just not su...