开发者

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 开发者_Python百科{ 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?


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


How about a server-side redirect?


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.


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>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜