ASP.NET MVC Routing , Html.BeginForm

半城伤御伤魂 提交于 2020-01-14 13:31:49

问题


<% using (Html.BeginForm("SearchByZip", "Dealer", new { zip = ""}, FormMethod.Get))
  { %>
<div>
<input type="text" class="padLeft" name="Zip" id="Zip" style="width: 200px" />
<input type="submit" class="btnFind" value="Find" />
</div>
<% } %>

This gives me the url "Dealer/SearchByZip?Zip=12345" I would like to end up with this: "Dealer/Zip/12345" (if I manually type in the url "Dealer/Zip/12345" it returns the right results, but when I click in submit it comes up with "Dealer/SearchByZip?Zip=12345" What am I missing?

routes.MapRoute(
            "DealerSearchByZip",
            "Search/Zip/{zip}",
            new { Controller = "Dealer", action = "SearchByZip", zip = "" }
         );

回答1:


This is happening because "Zip" is an input field in your form, not route data. So, when the page is rendered it creates a url using the default route ("DealerSearchByZip" route wasn't matched because Zip wasn't given as route data).

You could accomplish this via javascript, by updating the "action" attribute on the form when the "zip" field is updated. Example using jQuery:

$('input[name=Zip]').update(function(){
    $('form').attr('action', 'Dealer/Zip/' + $(this).val());
});

Or, since Zip is the only value you're worried about,

$('form').submit(function(){
    window.location = 'Dealer/Zip/' + $('input[name=Zip]').val();
});


来源:https://stackoverflow.com/questions/5918014/asp-net-mvc-routing-html-beginform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!