简体   繁体   中英

ASP.NET MVC Routing , Html.BeginForm

<% 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 = "" }
         );

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM