ASP.NET MVC routing: with querystring to one action, without to another

橙三吉。 提交于 2019-12-20 04:34:27

问题


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

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