ASP.NET MVC routing by string id?

孤街醉人 提交于 2019-12-21 07:23:12

问题


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:


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



来源:https://stackoverflow.com/questions/7618037/asp-net-mvc-routing-by-string-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!