问题
I need the following routes:
example.com/products
goes to a product categories page (e.g. cars, trucks, buses, bikes)
controller=Products
, action=Categories()
example.com/products?a=1&b=2
goes to an index of all products in a particular category (e.g. Ford, Honda, Chevy)
controller=Products
, action=Index(string a, string b)
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.
How do I differentiate between the two?
Edit: 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?
回答1:
Introduce Parameters. ASP.NET MVC allows you to create 'pretty' URLs, and that's exactly what you should do here:
First, the route mappings:
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
{
}
This will allow you to use a search-friendly URL and you don't have to worry about query string parameters.
来源:https://stackoverflow.com/questions/7395841/asp-net-mvc-routing-with-querystring-to-one-action-without-to-another