mvcNoob
mvcNoob

Reputation: 31

ASP.NET MVC url search parameter without question mark

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?

Upvotes: 3

Views: 2446

Answers (5)

JeremyWeir
JeremyWeir

Reputation: 24378

How about a server-side redirect?

Upvotes: 2

Victor Gelmutdinov
Victor Gelmutdinov

Reputation: 489

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

Upvotes: 0

thitemple
thitemple

Reputation: 6059

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>

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68707

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.

Upvotes: 1

&#199;ağdaş Tekin
&#199;ağdaş Tekin

Reputation: 16661

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

Upvotes: 2

Related Questions