Search Route in ASP.NET MVC

I have a simple search form on my main page and a controller and view. I am trying to get the following route for the search string "myterm" (for example): root / search / myterm

Form on the main page:

<% using (Html.BeginForm("SearchResults", "Search", FormMethod.Post, new { id = "search_form" })) { %> <input name="searchTerm" type="text" class="textfield" /> <input name="search" type="submit" value="search" class="button" /> <%} %> 

Controller action:

 public ActionResult SearchResults(string searchTerm){...} 

The route I am using:

 routes.MapRoute( "Search", "search/{term}", new { controller = "Search", action = "SearchResults", term = (string)null } ); routes.MapRoute( "Default", "{controller}/{action}", new { controller = "Home", action = "Index" } ); 

I always get the root / search URL without a search query, no matter what search query I enter.

Thanks.

+7
search asp.net-mvc action routes
source share
2 answers

You use id in your beginform tag and {term} in your route.

Both must match.

+3
source share

So, if I understand you correctly, you are trying to make a route to go to http://www.whatever.com/search/blah , and you will be redirected to the SearchResults action with the searchTerm parameter, which is "blah".

The following route will take care of this:

 routes.MapRoute( "Search", "search/{searchTerm}", new { controller = "Search", action = "SearchResults" } ); 

Make sure the route BEFORE the route is the default, or the first one will be selected by default. Note that the term “term” changes to “searchTerm” to match the parameter in your action. It's necessary.

+3
source share

All Articles