I am struggling with something that I’m not even sure if possible.
I have a typical form page in an .NET MVC 3 Razor project. Within this page is a Google map with a search mechanism. The search is wrapped with a form that calls a JavaScript function to update the map if a location is found.
When I try to use it, the view’s controller handles the request and the controller’s model state is not valid (as the user hasn’t finished with the rest of the form yet). The result is a representation of the page which resets the map (totally the opposite of what I’m after).
Here’s a simplified version of the view:
@model OnlineEventReporting.ViewModels.ReportShortViewData
@{
Layout = "~/Views/Shared/_LayoutGoogleMap_with_all_js_code.cshtml";
}
<script type="text/javascript">
function showAddress(address) { [processing code] }
</script>
@using (Html.BeginForm("Index", "ShortReport", FormMethod.Post, new { name = "shortForm", id = "shortForm", data_ajax = "false" }))
{
@Html.ValidationSummary(true)
Info for the controller to handle:
@Html.TextBoxFor(model => model.AddressDetail.Street1, new { @maxlength = "50" })
<!-- I want this to 'fire' the JavaScript 'showAddress' function and for the controller to ignore it -->
<form style="text-align:center" action="#" onsubmit="showAddress(this.address.value); return false">
<input type="text" size="20" id="address" name="address" value="North Street, Guildford" />
<input type="submit" value="Search!" />
</form>
<div id="map" style="width: 100%; height: 400px; margin-left:20px;"></div>
More info for the controller to handle:
@Html.TextBoxFor(model => model.AddressDetail.Street2, new { @maxlength = "50" })
}
I realise I have a form within a form here but I’m not how else I could approach this as I need the map and search feature right in the middle of my main form.
Any help would be greatly appreciated.
Many thanks,
Chris.
Your code would produce invalid HTML – nested forms are not valid HTML.
The problem is that the
input type="submit"probably causes the topmost form to submit instead of what you expect.Why not have a normal button and attach the function to the click event?