Search Route in ASP.NET MVC
I have a simp开发者_JAVA百科le search form in my master page and a serach controller and view. I'm trying to get the following route for the string search term "myterm" (for example): root/search/myterm
The form in the master 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" />
<%} %>
The Controller Action:
public ActionResult SearchResults(string searchTerm){...}
The Route I'm 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'm always getting the url "root/search" without the search term, no matter what search term I enter.
Thanks.
You're using id in your beginform tag and {term} in your route.
The two need to match.
So if I understand you correctly, you are trying to make a route so that you can go to http://www.whatever.com/search/blah and you will be routed to the SearchResults action with the searchTerm parameter being "blah".
The following route will take care of that:
routes.MapRoute(
"Search",
"search/{searchTerm}",
new { controller = "Search", action = "SearchResults" }
);
Make sure the route is BEFORE the default route or the default will be matched first. Notice that "term" is changed to "searchTerm" to match the parameter in your action. This is necessary.
精彩评论