Self-AJAX-updating partial-view/controller in ASP.Net MVC and the duplicating div Self-AJAX-updating partial-view/controller in ASP.Net MVC and the duplicating div ajax ajax

Self-AJAX-updating partial-view/controller in ASP.Net MVC and the duplicating div


The unobtrusive Ajax library that ships with .NET MVC 3 uses callbacks that are based on the four callbacks from jQuery.ajax. However, the InsertionMode = InsertionMode.Replace from the Ajax.BeginForm method does not result in jQuery's replaceWith being called. Instead, .html(data) is used to replace the contents of the target element (and not the element itself).

I have described a solution to this problem on my blog:http://buildingwebapps.blogspot.com/2011/11/jquerys-replacewith-and-using-it-to.html


Are you using an AjaxHelper.Form or jQuery. If you are using jQuery, have you tried using replaceWith()? Using AjaxHelper are you using AjaxOptions { InsertionMode = InsertionMode.Replace }? I would think that using either you would be able to replace the entire DIV with the results from the partial view.


Using

AjaxOptions { UpdateTargetId = "myDiv", InsertionMode = InsertionMode.Replace } 

should replace the whole content of '#myDiv' element, as tvanfosson says. Your problem is where is '#myDiv' located. Here's an example:

<div id="myDiv">    <% Html.RenderPartial("MyPartialView"); %></div>

where MyPartialView is:

<div id="comments">    <% using (Ajax.BeginForm(new AjaxOptions() { UpdateTargetId = "myDiv", InsertionMode = InsertionMode.Replace } )) {%>            ...    <input type="submit" value="Submit comment" />    <% } %></div>

If you include '#myDiv' div inside the partial view, it will be rendered right after receiving the response (together with its content), and then it's content will be replace with the response which is the same partial view (including its own '#myDiv' div), and that's why you always end up with 2 nested divs.

You should always use a container for your partial views and then set the UpdateTargetId to the container id.

Edit: I updated the code to represent the exact situation you describe in your question.