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: "Dealer / Zip / 12345" (if I manually type the url "Dealer / Zip / 12345", it returns the correct results, but when I click on the "Submit" button, "Dealer / SearchByZip? Zip = 12345" appears, What am I missing?
routes.MapRoute( "DealerSearchByZip", "Search/Zip/{zip}", new { Controller = "Dealer", action = "SearchByZip", zip = "" } ); +4
1 answer
This is because "Zip" is an input field in your form, not a data routing. Thus, when the page is displayed, it creates a URL using the default route (the route "DealerSearchByZip" was not mapped because Zip was not specified as route data).
You can accomplish this through javascript by updating the action attribute on the form when the zip field is updated. An example of 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(); }); +3