5

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

p.campbell
  • 98,673
  • 67
  • 256
  • 322
harropriiz
  • 455
  • 1
  • 4
  • 10

2 Answers2

5

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
  • 56,753
  • 31
  • 116
  • 165
  • Daniel has put this quite nicely - you can't force the form to make a get request and alter URL for you. – mare May 03 '10 at 14:50
  • Implemented the js click event to redirect. I used the http://www.digitalbart.com/jquery-and-urlencode/ which is pretty cool. – harropriiz May 03 '10 at 16:56
0

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

arena-ru
  • 990
  • 2
  • 12
  • 25
  • This requires an extra round trip between the server and client for the sake of formatting a url. Not recommended. – Daniel Schaffer May 03 '10 at 14:44
  • 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. – arena-ru May 03 '10 at 22:48