14

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?

1 Answer 1

20

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).

Sign up to request clarification or add additional context in comments.

6 Comments

And be sure to put it before the default route, otherwise it will never get hit.
Unfortunately that breaks several of my automatic routes because they match the regex, eg /Product/List etc. Do I need to add a route for List before this new route? How do I create a basic route?? Because they are automatic I don't actually know how.
Yes, you have to order things as the first route that matches will be used. The default route matches {controller}/{action}/{id}. You can explicitly list routes before this one like {controller}/list/ or {controller}/otherAction/{id} and those will match first (only if second segment of path is "list" or "otherAction").
Sorry it doesn't work: /Product/1 is matching the new route with the regex. Does \w+ include digits perhaps?
My mistake, yes \w matches numbers as well... regular-expressions.info/reference.html
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.