Search code examples
ajaxasp.net-mvcunobtrusive-ajax

Get calling form in OnSuccess


<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?


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