3
votes

I have a route defined as:

routes.MapRoute("AllUsers",
"Users/Search/{Search}", new { Controller = "Users", action= "Index"});

and the form as:

<% using (Html.BeginForm("Index", "Users/Search/", new { RouteValue = "AllUsers" }, FormMethod.Get, new { id = "searchForm" })){%>
 <input id="searchBox" name="search" type="text" />
 <input type="submit" id="submit" value="Search" /><%} %>

Currently as expected this creates a url of
../Users/Search/?search=searchTerm
but what I would like is:
../Users/Search/searchTerm

How is this possible? I thought of using javascript, but this seems a little dirty. Is there a more streamlined way of accomplishing this?

5

5 Answers

2
votes

You cannot do that with an HTML form. Though you can mimic the behavior with JavaScript.

2
votes

How about a server-side redirect?

1
votes

You could do:

<input type="submit" id="submit" value="Search" 
    onclick="$('form').attr('action', $('form').attr('action') + $('#searchBox').val());" />

Which seems a little ugly. You could also not use a form and have this:

<input type="button" id="submit" value="Search" 
    onclick="window.location.href = 'search/' + $('#searchBox').val();" />

Outside of this, you could allow the original submit to go to the weird url, but use RedirectToAction in your controller.

0
votes

Using jQuery you could something like this:

<script type="text/javascript">
        $(function(){
            $("#submit").click(function(){
                document.location.href = $("form").attr("action") + $("#searchBox").val();
                return false;
            });
        });
    </script>
0
votes

Try to change like this:

routes.MapRoute("AllUsers",
"Users/Search/{id}", new { Controller = "Users", action= "Index"});

and the form as:

<% using (Html.BeginForm("Index", "Users/Search/", 
  new { RouteValue = "AllUsers" }, FormMethod.Get, new { id = "searchForm" })){%>
  <input id="searchBox" name="id" type="text" />
  <input type="submit" id="submit" value="Search" /><%} %>

Not tested, but "id" is default route value which are not creating "?name=value".