3

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 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

How about a server-side redirect?

Comments

1

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.

Comments

0

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.