Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC URL Routing with Multiple Route Values

I am having trouble with Html.ActionLink when I have a route that takes more than one parameter. For example, given the following routes defined in my Global.asax file:

routes.MapRoute(     "Default",                                              // Route name     "{controller}.mvc/{action}/{id}",                           // URL with parameters     new { controller = "Home", action = "Index", id = "" }  // Parameter defaults );  routes.MapRoute(     "Tagging",     "{controller}.mvc/{action}/{tags}",     new { controller = "Products", action = "Index", tags = "" } );  routes.MapRoute(     "SlugsAfterId",     "{controller}.mvc/{action}/{id}/{slug}",     new { controller = "Products", action = "Browse", id = "", slug = "" } ); 

The first two routes work without a problem, but when I try to create an action link to the third route using:

<%= Html.ActionLink(Html.Encode(product.Name), "Details", new { id = product.ProductId, slug = Html.Encode(product.Name) }) %> 

I end up with a URL like [site-root]/Details/1?slug=url-slug whereas I would like the URL to be more like [site-root]/Details/1/url-slug

Can anyone see where I am going wrong?

like image 932
Ian Oxley Avatar asked Apr 09 '09 13:04

Ian Oxley


People also ask

Can we have multiple routes in MVC?

Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.

How many routes can be defined in the MVC 3 application?

there are no limits in creating routes. You can create as many route as you want in your RouteConfig.

How are URL patterns mapped to a handler in ASP.NET MVC?

Typical URL Patterns in MVC Applications URL patterns for routes in MVC Applications typically include {controller} and {action} placeholders. When a request is received, it is routed to the UrlRoutingModule object and then to the MvcHandler HTTP handler.


2 Answers

It is using the first route that is fully satisfied. Try putting your SlugsAfterId route above the Default one.

It's basically going: "Check Default. Got an action? Yes. Got an id? Yes. Use this one and chuck any other parameters in the querystring."

As a side note, doing that will make your Default route redundant as you provide a default value for the slug parameter.

like image 106
Garry Shutler Avatar answered Sep 19 '22 10:09

Garry Shutler


Garry (above) is correct. You can use Mr. Haack's route debugger for MVC. It can help resolve routing issues by showing you which routes are hit and when.

Here is the Blog Post. And here is the Zip File.

like image 45
MunkiPhD Avatar answered Sep 21 '22 10:09

MunkiPhD