Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC routing by string id?

In ASP.NET 2, how do I create a route that allows lookup of an object (eg Product) by a string id (eg ProductCode)? The route for looking up the same object by it's integer id (eg ProductId) is automatic, so I don't actually know how it works.

The automatic route by id is:

/Product/1

How do I also create a 2nd route that uses a string id?

/Product/red-widget

And how do I do it so that both routes are available?

like image 787
JK. Avatar asked Oct 01 '11 03:10

JK.


1 Answers

You should take a look at using a route constraint to do this. See http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="DetailsByName"},
    new {productId = @"\w+" }
 );

In the above, the constraint regex "\w+" should limit to routes that match only "word" characters (take a look at regex docs for more details on patterns used here).

like image 156
craigb Avatar answered Sep 28 '22 06:09

craigb