4

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 }
    );
}
CarenRose
  • 1,266
  • 1
  • 12
  • 24
Ahmad
  • 343
  • 1
  • 3
  • 12
  • Do you want these routes to match multiple controllers or just the ShoppingManagement one? Your problem is that currently both of these route definitions are identical - string / string / string, so they will all get picked up by the top route. – Richard Apr 22 '13 at 05:29

1 Answers1

13

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 }
        );

    }
Virus
  • 2,445
  • 1
  • 14
  • 17
  • I want use first format for special controller and other controller use second format. how can I do it? – Ahmad Apr 22 '13 at 05:36
  • Yes by making the first route with a fixed Controller in the url pattern you can achieve this... see the code in the answer it has "ShoppingManagement" controller into the url pattern, so whichever url will have ShoppingManagement as the 2nd parameter will match this route, others will match the other route. – Virus Apr 22 '13 at 05:40
  • I did it but i got this error "The matched route does not include a 'controller' route value, which is required." – Ahmad Apr 22 '13 at 06:10
  • plz provide the actual url on which you want to match the first route. – Virus Apr 22 '13 at 06:41
  • localhost:3681/ABCD/ShoppingManagment/ShoppingManagment/ – Ahmad Apr 22 '13 at 06:57
  • plz check the update, you will need to add controller="ShoppingManagment" in the defaults of the first route. – Virus Apr 22 '13 at 07:06