views:

219

answers:

2

Hi,

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 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

A: 

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

Al Katawazi
Gaz Newt
Well if you have no objection and you want a clean url you should use a post instead of a get when you form submits. Otherwise if you setup your routing properly in the global.asax your url should look fine. ex: "{controller}/{action}/{id}/{page}"
Al Katawazi
A: 

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 = "" });
Gaz Newt