MVC Ajax.BeginForm Replace Strange Behavior
In a partial view, I use Ajax.Beginform MVCs, for example:
<div id="divToReplace"> @using (Ajax.BeginForm("Action", "Controller, new AjaxOptions { InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, UpdateTargetId = "divToReplace" }, new { id = "formID" })) { ... </div> When submitting the form, I would expect to divide the div "divToReplace" is replaced by the answer (partial view again). But instead, the inner html div "divToReplace" is replaced with the response, so the beginning of the partial view looks like this:
<div id="divToReplace"> <div id="divToReplace"> ... What am I doing wrong?
Well, after some time I ran into the same problem, and now I wanted to clarify this, so I looked in jquery.unobtrusive-ajax.js and the corresponding function:
function asyncOnSuccess(element, data, contentType) { var mode; if (contentType.indexOf("application/x-javascript") !== -1) { // jQuery already executes JavaScript for us return; } mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase(); $(element.getAttribute("data-ajax-update")).each(function (i, update) { var top; switch (mode) { case "BEFORE": top = update.firstChild; $("<div />").html(data).contents().each(function () { update.insertBefore(this, top); }); break; case "AFTER": $("<div />").html(data).contents().each(function () { update.appendChild(this); }); break; default: // Changed this line because of generating duplicate IDs //$(update).html(data); $(update).html($(data).html()); break; } }); } As you can see in the default part, the answer did not replace updatetargetid, but replaced its contents with the answer. Now I take the inside of the answer and everything works fine!
In addition to the previous answer, you can add your own condition to jquery.unobtrusive -
ajax.js: case "REPLACEWITH": $(update).replaceWith(data); break; and pass your own parameter with HtmlAttributes:
@using (Ajax.BeginForm("Action", "Controller", null, new AjaxOptions {UpdateTargetId = "DivContainer" } new { enctype = "multipart/form-data", data_ajax_mode = "replacewith" }