Question mark ASP.NET MVC URL search parameter

I have a route defined as:

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

and the form:

<% 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 ../Users/Search/?search=searchTerm
but I would like to:
../Users/Search/searchTerm

How is this possible? I was thinking about using javascript, but that seems a bit messy. Is there a better way to accomplish this?

+3
source share
5 answers

You cannot do this with an HTML form. Although you can simulate JavaScript behavior.

+2

?

+2

:

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

. :

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

In addition, you can allow the original send to go to a strange URL, but use RedirectToAction in your controller.

+1
source

Using jQuery, you can something like this:

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

Try changing like this:

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

and the form:

<% 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 verified, but "id" is the default default value that does not create "? Name = value".

0
source

Source: https://habr.com/ru/post/1734109/


All Articles