views:

85

answers:

2

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

+4  A: 

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.

Daniel Schaffer
Daniel has put this quite nicely - you can't force the form to make a get request and alter URL for you.
mare
Implemented the js click event to redirect. I used the http://www.digitalbart.com/jquery-and-urlencode/ which is pretty cool.
A: 

Or you can make FormMethod.Post and in your controller return RedirectToActionResult

mmcteam.com.ua
This requires an extra round trip between the server and client for the sake of formatting a url. Not recommended.
Daniel Schaffer
Yes it is, extra call but using js is not nice way too.And also it is recommended not to leave user on same page where some changes to data was made(delete, edit, add) so by pressing f5 you will be asked to send data one more time. And take a look - http://stackoverflow.com/questions/1936/how-to-redirecttoaction-in-asp-net-mvc-without-losing-request-data - people are using it.
mmcteam.com.ua