asp.net-mvcasp.net-mvc-routingmaproute

Registering Multiple Routes in MVC asp.net


I want to map several routes in MVC that have the parameters in different orders:

localhost:1010/abcd/home/index
localhost:1010/home/index/abcd

id=abcd
controller=home
action=index

I tried the code below, but it doesn't work.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "ShoppingManagment",
        "{id}/{controller}/{action}",
        new { controller = "ShoppingManagment",
            action = "ShoppingManagment", id = UrlParameter.Optional });


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

Solution

  • It will not work because both routes have the same format.

    So the MVC Routing Engine cannot differentiate between both the url patterns.

    Try writing the Controller directly into the url pattern.

    public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapRoute(
              "ShoppingManagment",
              "{id}/ShoppingManagment/{action}",
              new { controller="ShoppingManagment", action = "ShoppingManagment", id = UrlParameter.Optional });
    
    
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home",
                 action = "Index", id = UrlParameter.Optional }
            );
    
        }