ASP.NET MVC : Ignore latter route elements in url for a form's action
I have a URL /products/search where Products is the controller and Search is the action. This url contains a search form whose action attribute is (and should always be) /products/search eg;
<%using( Html.BeginForm( "search", "products", FormMethod.Post))
This works ok until I introduce paging in the search results. For example if I search for "t" I get a paged list. So on page 2 my url looks like this :
/products/search/t/2
It shows page 2 of the result set for the search "t". The problem is that the form action is 开发者_C百科now also /products/search/t/2. I want the form to always post to /products/search.
My routes are :
routes.MapRoute( "Products search",
"products/search/{query}/{page}",
new { controller = "Products", action = "Search", query = "", page = 1 });
routes.MapRoute( "Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
How can I force Html.BeginForm(), or more specifically Url.Action( "Search", "Products"), to ignore the /query/page in the url?
Thanks
Fixed by adding another route where query and page are not in the url which is kind of counter intuitive because the more specific route is lower down the order
routes.MapRoute(
"",
"products/search",
new { controller = "Products", action = "Search", query = "", page = 1 });
routes.MapRoute(
"",
"products/search/{query}/{page}",
new { controller = "Products", action = "Search"} //, query = "", page = 1 });
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
The order is really important, the first route it hits that matches it uses. Therefore catch all type routes should be at the very end. Here is a helpful route debugger youc an use to figure out what the problem is.
Route Debugger
精彩评论