问题
<% 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