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 }
    );
}
1
  • 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. Commented Apr 22, 2013 at 5:29

1 Answer 1

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

    }
Sign up to request clarification or add additional context in comments.

6 Comments

I want use first format for special controller and other controller use second format. how can I do it?
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.
I did it but i got this error "The matched route does not include a 'controller' route value, which is required."
plz provide the actual url on which you want to match the first route.
localhost:3681/ABCD/ShoppingManagment/ShoppingManagment/
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.