clockwiseq
clockwiseq

Reputation: 4229

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.

Upvotes: 3

Views: 2080

Answers (2)

Abdul Rahim
Abdul Rahim

Reputation: 169

If you are using the same controller name for Area and default one(For eg: HomeController). Use the namespaces for that

context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new {
                    area = "Admin",
                    controller = "Home",
                    action = "Index", id = UrlParameter.Optional },
                namespaces: new[] { "{{Namespace}}.Areas.Admin.Controllers" }
            ); 

for default one

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new {  controller = "Home", 
                action = "Index", 
                id = UrlParameter.Optional },
                namespaces: new[] { "{{Namespace}}.Controllers" }
            );

Upvotes: 1

Erik Philips
Erik Philips

Reputation: 54638

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.

Upvotes: 4

Related Questions