ASP.NET MVC search route
I setup a search route:
routes.MapRoute(
"Search",
"Search/{q}",
new { controller = "Search", action = "Index" }
);
The search form has an input box and a button. I want the search with a GET as below.
<% using(Html.BeginForm("Index", "Search",开发者_StackOverflow中文版 FormMethod.Get))
{%>
<%:Html.TextBox("q")%>
<span class="query-button">
<input type="submit" value="select" /></span>
<% } %>
</div>
The action on the SearchController is:
public ActionResult Index(string q)
{
// search logic here
return View(new SearchResult(q));
}
The URL becomes like this: http://localhost:19502/search?q=mvc+is+great
But I want the search to be like: http://localhost:19502/search/mvc+is+great
How do I setup the route or the Html.BeginForm
There isn't a straightforward way to do it with just a form. A form's intended function is to transmit name/value pairs - using MVC doesn't change that.
So your options are:
- Override the functionality of the form using Javascript by handling the submit event of the form, redirecting to the desired URL and returning false to prevent the form from actually submitting
- Don't use a form and handle the click event of a button to do the redirect.
Your route is already correctly set up to handle this.
Or you can make FormMethod.Post and in your controller return RedirectToActionResult
精彩评论