我的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" />
}
我希望在使用“Save&amp; Next”按钮提交表单后调用另一个js函数。因此,如果用户单击“保存”按钮,则应提交表单,然后调用“closeForm”javascript函数。如果用户单击“Save&amp; Next”按钮,则应提交表单,然后调用“nextForm”javascript函数。有没有一种简单的方法来实现这一目标?
答案 0 :(得分:8)
有没有一种简单的方法可以达到这个目的?
不,但您可以让控制器操作通过结果中单击的按钮。这可以作为Json属性(如果您返回JSON)完成,也可以是自定义响应HTTP标头。
然后在你的成功回调中(只能是一个)你可以检索这个值,以便知道点击了哪个按钮并采取相应的行动。
所以,首先给你的提交按钮命名,以便你知道点击了哪一个:
@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>
}
然后进入你的控制器动作
[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
}
}
}
答案 1 :(得分:1)
您可以从Ajax.BeginForm()切换到Html.BeginForm(),然后使用JQuery提交表单。
<script type="text/javascript">
$('#save').on('click', function () {
var form = $('form');
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function (result) {
// call another function
}
});
return false;
});
$('#saveAndEdit').on('click', function() {
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function (result) {
// call another function
}
});
return false;
});
</script>
答案 2 :(得分:0)
你也可以这样写:
@using (Ajax.BeginForm("Save", "Company", new AjaxOptions() {
HttpMethod="Post", OnSuccess="closeForm"
}, new { id = "companyEditForm" })) {
<input type="submit" onclick="showNextForm = true;">Save & Next</button>
<input type="submit" onclick="showNextForm = false;">Save</button>
}
...
var showNextForm = false;
function closeForm(data) {
if(showNextForm) {
nextForm();
}
else {
// do your stuff
}
}