Question

<div class=".parentForm'>
    @Ajax.BeginForm(... AjaxOptions { OnSuccess = "submitSuccess" })
    {...}
</div>

function postDone(result,two, three) {
   $('.parentForm').replaceWith(result);
}

I don't like this because if there are multiple forms from this partial they will all have the same class, and I would rather not come up with some funky scheme where I generate an ID on the server side and have to pass it around to the JS callbacks.

With .ajax I can use the this to get the form that submitted the request, then from there get the parent .formContainer. Is there any way to get a referrence to the form that submitted the form with OnSuccess?

Was it helpful?

Solution

Actually there is an easier way though you still have to modify the jquery.unobtrusive-ajax.js file. Add one line of code around line # 100. I provided the same answer here

options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });

options.context = element; // <--- Add this line

method = options.type.toUpperCase();
if (!isMethodProxySafe(method)) {
    options.type = "POST";
    options.data.push({ name: "X-HTTP-Method-Override", value: method });
}

Update: AaronLS has created an issue on codeplex to see if they would make the change to the jQuery Unobtrusive Ajax file itself, upvote it if you would like this change added as well!

Codeplex Issue: Let 'this' reference the source element

OTHER TIPS

Of course, but you need to modify jquery.unobtrusive-ajax.js file. You must replace the following lines:

success: function (data, status, xhr) {
    asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");       
    getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(this, arguments);
},

with:

success: function (data, status, xhr) {
    asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
    var args = $.merge(arguments, [element]);
    getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(this, args);
},

can access form in that way:

function submitSuccess(result, status, xhr, element) {
    // element is your form
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top