MVC5 custom route to remove controller name from scope

I can't get the job done yet and need help. I have a basic MVC 5 site and I added an area called Administration. For my life, I can't figure out how to properly set the default controller / action for a scope.

In my site I have a realm named Admin, a controller named Admin (with index and view) and this is the realm 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 http://myapplication/Admin

and it displays the view I set (Admin / Index) and the url remains http://myapplication/Admin

(which is what I want). Now, with this added, it splits any further routing to the controller. So when I try 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 route the route http://myapplication/Admin/Menu/Create

correctly, but also need to keep the default controller / action for this scope.

+3


source to share


2 answers


You should just 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 default values, you should be able to call /Admin/

, and the rest of the parameters are default.

+4


source


If you are using the same controller name for scope and default (for example HomeController). Use namespaces for this

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

      



default

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

      

+1


source







All Articles