我的 MVC 页面上有一个 Ajax 表单,带有两个单独的提交按钮...
@using (Ajax.BeginForm("Save", "Company", new AjaxOptions() {
HttpMethod="Post", OnSuccess="closeForm"
}, new {@id = "companyEditForm"})) {
....some edit fields......
<input type="submit" value="Save & Next"/>
<input type="submit" value="Save" />
}
我想在使用“保存并下一步”按钮提交表单后调用不同的 js 函数。因此,如果用户单击“保存”按钮,则应提交表单,然后调用“closeForm”javascript 函数。如果用户单击“保存并下一步”按钮,则应提交表单,然后调用“nextForm”javascript 函数。有实现此目的的简单方法吗?
最佳答案
Is there a simple way of achieving this?
不,但是您可以让 Controller 操作传递在结果中单击的按钮。这可以作为 Json 属性(如果您返回 JSON)来完成,也可以是自定义响应 HTTP header 。
然后在您的成功回调(只能是一个)中,您可以检索此值以了解单击了哪个按钮并采取相应行动。
因此,首先为您的提交按钮命名,以便您知道点击了哪个按钮:
@using (Ajax.BeginForm("Save", "Company", new AjaxOptions() {
HttpMethod="Post", OnSuccess="onSuccess"
}, new { id = "companyEditForm" })) {
....some edit fields......
<button type="submit" name="btn" value="save_next">Save & Next</button>
<button type="submit" name="btn" value="save">Save</button>
}
然后在你的 Controller Action 中
[HttpPost]
public ActionResult Save(MyViewModel model)
{
Response.AppendHeader("X-Button", Request["btn"]);
... your usual processing
}
最后在您的 onSucecss
回调中:
function onSuccess(data, status, xhr) {
function onSuccess(data, status, xhr) {
var btn = xhr.getResponseHeader('X-Button');
if (btn == 'save_next') {
// The "Save & Next" button was clicked
} else if (btn == 'save') {
// The "Save" button was clicked
} else {
// The user didn't submit the form by using the mouse and
// clicking on a button, he simply pressed Enter while
// inside some text field or you have some other portion of
// javascript which triggered the form submission without pressing
// on any submit button
}
}
}
关于javascript - Ajax.BeginForm 中的两个提交按钮。需要在OnSuccess中调用不同的js函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14980483/