0

I am trying to pass a parameter in mvc after the controller name

I added

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

This did not work

I also tried url: "Product/{id}",

But if i remove the lines above it(the lines below in this post), it is working

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

2 Answers 2

3

Order in which you register your routes matter. The first route that matches the request is used. If I understand that correctly, you originally had:

routes.MapRoute(
    name: "Default",
...

routes.MapRoute(
    name: "Product",

Default route is very generic, and since it was registered first it was picked up all the time for all of your requests, effectively shadowing the Product route.

Correct way to registed routes is to start with most specific ones, and have the most generic registered at the end. So in your case it should be reversed:

routes.MapRoute(
    name: "Product",
...
routes.MapRoute(
    name: "Default",
Sign up to request clarification or add additional context in comments.

Comments

1

In this case, it makes more sense to make the "id" parameter a required parameter, not an optional parameter. You probably also don't want it to be a slug ({*id}). This will help to ensure if your Product route does not match the request, the routing framework will try the next route in the list (in this case Default).

To be absolutely sure it will miss when there is no match, you could also add a route constraint to ensure the "id" is numeric, just like the route constraint example on MSDN.

routes.MapRoute(
    name: "Product",
    url: "Product/{id}",

    // id has no default value, which makes it required in order to match
    defaults: new { controller = "Product", action = "Index" },

    // (optional) adding a constraint will make sure the id is only digits
    constraints: new { id = @"\d+" }
);

// You will only end up here if the above route does not match, 
// so it is important that you ensure that it CAN miss.
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.