Routing ASP.NET MVC URLs with Multiple Route Values

I am having problems with Html.ActionLink when I have a route that takes more than one parameter. For example, given the following routes defined in the 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 problems, 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) }) %> 

Am I getting 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'm wrong?

+50
asp.net-mvc url-routing
Apr 09 '09 at 13:33
source share
3 answers

He uses the first route, which is completely satisfied. Try putting the SlugsAfterId route above Default .

This basically happens: "Check the default value. Got an action? Yes. Got an identifier? Yes. Use this and run any other parameters in the query string."

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

+59
Apr 09 '09 at 13:36
source share

Harry (above) is true. You can use Mr. Route Debugger Haack for MVC. This can help solve routing problems by showing you which routes go and when.

Here is a blog post . And here is the Zip File .

+31
Apr 09 '09 at 13:39
source share

You can add a restriction to your Routes containing "id", as it supposedly should only accept a number. Thus, the first route will only match when the "id" is numeric, then it will make the second route for all other values. Then put the one that includes {slug} at the top, and everything should work correctly.

 routes.MapRoute( "SlugsAfterId", "{controller}.mvc/{action}/{id}/{slug}", new { controller = "Products", action = "Browse", id = "", slug = "" }, new { id = @"\d+" } ); routes.MapRoute( "Default", // Route name "{controller}.mvc/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" }, // Parameter defaults new { id = @"\d+" } ); routes.MapRoute( "Tagging", "{controller}.mvc/{action}/{tags}", new { controller = "Products", action = "Index", tags = "" } ); 
+8
Jun 22 '09 at 21:17
source share



All Articles