Ashish Charan
Ashish Charan

Reputation: 2387

MVC 5 Ajax Form

I'm using Ajax.BeginForm helper. It works well but I have a small issue.

Here is the code:

<div class="row" id="pdiv">
@using (Ajax.BeginForm("SomeAction","SomeController",new AjaxOptions{UpdateTargetId="pdiv"}))
{
.....
}
</div>

I've set the UpdateTargetId to "pid".

So initially rendered HTML looks like:

<div class="row" id="pdiv">
<form action="/SomeController/SomeAction" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#pdiv" id="form0" method="post">
....

Now When I do a submit it places the entire pid div inside the pid. i.e.

<div class="row" id="pdiv">
    <div class="row" id="pdiv">
    <form action="/SomeController/SomeAction" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#pdiv" id="form0" method="post">
    .....
    }

I tried setting the Ajax Option InsertionMode= InsertionMode.Replace But no success. Is there anyway by which i can complete replace the "pdiv" with the newly obtained content?

Upvotes: 0

Views: 5185

Answers (2)

Nilesh Gajare
Nilesh Gajare

Reputation: 6398

As per this Post in StackOverflow by Simon

Well, after a certain time, I ran into the same problem and now I wanted to make it clear so I had a look in jquery.unobtrusive-ajax.js and the responsable 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 was not replacing the updatetargetid but replaced its content with the answer. Now I take the inner part of the answer and everything works fine!

Upvotes: 1

Alexandr Mihalciuc
Alexandr Mihalciuc

Reputation: 2577

You need to move the your ajax form markup to a separate view, so i t wouldn't have the div element you specify in target id, then you should server that new partial view from your ajax Action.

Upvotes: 1

Related Questions