I am working with MVC trying to load the results of a form submission into a specific DIV. Below is the code of my form:
<div class="segmentForm clearfix">
<% using (Ajax.BeginForm("ShopByAirCriteria", "AirOption", new AjaxOptions { UpdateTargetId = "DynamicAirOptions", InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnBegin = "return loadingBar();" }, new { @name = "AirOptionSegment_Air" }))
{ %>
<%
Html.RenderPartial("AirOneWay", Model);
%>
<br/>
<div class="agent-actions">
<a href="" class="btn blue" style="margin-right: 25px;">Load Original Data</a>
<input type="submit" class="btn green" id="a1" name="SearchAir" value="Search" />
</div>
<% } %>
</div>
I have included the necessary js files in my site master:
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")%>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")%>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>"></script>
But somehow, the Partial view that is rendered by the AirOption/ShopByAirCriteria action method is not being loaded in the DynamicAirOptions div but in a new page.
Any idea on what the issue might be? It was working properly when I was using the html.BeginForm helper, but I changed it to use the ajax helper instead because I need to load the results into a specific div. Is there any way to specify the TargetID with the html helper?
I would caution against using
Ajax.BeginForm
. It's a bit of a hold-over from Web Forms, and in my humble opinion, should never be used under any circumstances. It hides logic and therefore leads the developer pretty inevitably into a situation like yours, where it's not working and there's no obvious reason why. Explicit is always better than implicit; when you control the AJAX call, you'll always know why it does or does not work.So, just use a regular
Html.BeginForm
and then tie into the submit event with some custom JavaScript. Make your AJAX call to submit the form in your event handler and then render the resulting response to the page in the div you want. Since you're already using jQuery, this is super simple:A side benefit to this approach is that you're not crippling the standard form. It's still just a regular old form, so if JavaScript is disabled, or not available at all (such as with many screen readers used for the blind), the form can still submit the standard old way and return a new page with the results.
Have you include jquery before jquery.unobtrusive-ajax.js? it could be also some javascript error, check Console in your browser developer tool. I've paste your code in blank mvc4 app and works as expected.
Master:
View: