ASP.NET MVC路由通过字符串ID? [英] ASP.NET MVC routing by string id?
问题描述
在ASP.NET 2.0,我如何创建一个字符串ID(如产品code)允许一个对象(如产品)的查找路径?通过它查找同一目标的路由的整数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.
根据ID自动路线是:
/Product/1
我怎么也创建一个使用字符串ID的第二条路?
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?
推荐答案
您应该看一看在使用路由约束来做到这一点。见<一href=\"http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs\">http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs
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+" }
);
在上面,约束正则表达式\\ 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).
这篇关于ASP.NET MVC路由通过字符串ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!