Search code examples
asp.net-mvcasp.net-mvc-routingasp.net-mvc-areas

MVC5 Custom Route to Remove Controller Name from Area


So far I can't make this work and I need some assistance please. I have a basic MVC 5 site, and I have added an area called Administration. For the life of me, I can't figure out how to set a default controller/action for an area, properly.

In my site, I have an area named Admin, a controller named Admin (with Index method and view), and this is the area registration:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.MapRoute(
        name: "Admin_base",
        url: "Admin",
        defaults: new { area = "Admin", controller = "Admin", action = "Index", id = UrlParameter.Optional }
    );

    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}

The first MapRoute allows me to browse to http://myapplication/Admin and it displays a view that I set (Admin/Index) and the URL stays http://myapplication/Admin (which is what I want). Now, by adding this, it breaks any further routing to a controller. So when I attempt to navigate to the Menu controller in the Admin area, it fails.

Is there a correct way to do this?

i.e. I need to make http://myapplication/Admin/Menu/Create route properly, but also need to retain the default Controller/Action for the area.


Solution

  • You should just be able to combine them into one:

    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        defaults: new { area = "Admin", 
                        controller = "Admin", 
                        action = "Index", 
                        id = UrlParameter.Optional }
    );
    

    By assigning defaults, you should be able to call /Admin/ and the rest of the parameters are set to the defaults.