1

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

2 Answers 2

1

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 = "" });
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Thanks, the problem then is that the search query and page values appear as query parameters in the url like this : /products/search?query=r&page=2 rather than /products/search/r/2 So it seems like a routing catch 22
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}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.