Briskstar Technologies
Briskstar Technologies

Reputation: 2253

ASP.Net MVC Routing issue for Home controller

I have created one sample internet MVC application. Then created ProductsController with Index view.

Then in routing, I mapped product url with products/prodname/id with below routing rules.

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

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

But after this, contact page redirects me to home index controller action. ?? why so? Am I missing something and why other actions stopped working after creating only one rule for product.

Upvotes: 0

Views: 1772

Answers (1)

dom
dom

Reputation: 6832

Change your first route to something like

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

Otherwise that route will pretty much match anything. Remember that the order of your routes is important, as matching will be attempted in that order.

Edit :

The reason for this being that by default the routing handler makes no difference between {controller}/{name} and {controller}/{action}. They're the same format, only with different parameter names.

Here's a breakdown of what happens for say a given URL such as /Home/Index.

First route will be attempted first, has 4 parameters, 2 of which are optional so no values will be given if they're not present, leaving you with the following values :

  • controller : Home
  • name : Index
  • action : null but will default to Index as specified
  • id : null

As you can see both non-optional parameters are filled, therefore the route will match, but will not function as you might have expected. Same thing would happen no matter what the URL is, as long as it has a value for controller and name. Which brings me to my original answer, if you want that first route to match only incoming URLs for products, you need to add something that will allow the routing handler to differentiate it. By replacing {controller} with a hard-coded value of products, now that route will only match incoming URL's starting with products, leaving anything else to keep going down the route chain as expected.

Hope that clears it up for you.

Upvotes: 3

Related Questions