Get calling form in OnSuccess

吃可爱长大的小学妹 提交于 2019-12-11 10:15:59

问题


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


回答1:


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




回答2:


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
}


来源:https://stackoverflow.com/questions/14655280/get-calling-form-in-onsuccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!