ASP.NET MVC路由:与查询字符串到一个动作,但无其他 [英] ASP.NET MVC routing: with querystring to one action, without to another
问题描述
我需要以下路线:
example.com/products
结果
都到了产品类别页面(例如汽车,卡车,公交车,自行车)结果
控制器= 产品
,行动= 类别()
example.com/products?a=1&b=2
结果
去所有产品的指数在一个特定的类别(如福特,本田,雪佛兰)结果
控制器= 产品
,行动= 指数(字符串,字符串B)
的路由仅在查询字符串不同,它似乎是MVC忽略?后的任何东西。所以当然只有一个规则将永远得到击中 - 第一个
The routes only differ on the querystring, and it seems that MVC ignores anything after the "?". So of course only one rule will ever get hit--the first one.
我如何区分这两种?
编辑:换句话说,我要两条路线。是否有可能使用的查询字符串中的路线还是MVC真正忽略它?有什么办法破解它,或者使用某种自定义的路由方案,就像我可以做定制的绑定和自定义的验证?
stated differently, I want two routes. Is it possible to use the querystring in the route or does MVC truly ignore it? Is there any way to hack it, or use a custom routing scheme of some kind, much like I can do custom binding and custom validation?
推荐答案
介绍参数。 ASP.NET MVC允许你创建'pretty的URL,而这正是你应该做的是什么在这里:
Introduce Parameters. ASP.NET MVC allows you to create 'pretty' URLs, and that's exactly what you should do here:
首先,路由映射:
routes.MapRoute(
"SpecificProducts",
"products/{a}/{b}",
new { controller = "products", action = "Categories" }
);
routes.MapRoute(
"ProductsIndex",
"products".
new { controller = "products", action = "Index" }
);
然后,控制器操作
Then, the controller actions
public ActionResult Index()
{
}
public ActionResult Categories(string a, string b) //parameters must match route values
{
}
这将允许您使用搜索友好的URL,你不必担心查询字符串参数。
This will allow you to use a search-friendly URL and you don't have to worry about query string parameters.
这篇关于ASP.NET MVC路由:与查询字符串到一个动作,但无其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!