在我的MVC视图我有按钮:
<input id="btnSave" type="submit" name="Save" value="Save" />
当我点击这个按钮我需要调用一个动作,做一些东西,然后提交我的表单.
我有这个jQuery:
$('#btnSave').click(function () { $.ajax({ url: "/Home/SaveDetailedInfo",type: "POST",data: JSON.stringify({ 'Options': someData}),dataType: "json",traditional: true,contentType: "application/json; charset=utf-8",success: function (data) { if (data.status == "Success") { alert("Done"); } else { alert("Error occurs on the Database level!"); } },error: function () { alert("An error has occured!!!"); } }); });
然后我想提交我的表单.在控制器我有2个操作:
public ActionResult SaveDetailedInfo(Option[] Options) { return Json(new { status = "Success",message = "Success" }); } [HttpPost] public ActionResult Save() { return RedirectToAction("Index","Home"); }
问题是当我在我的按钮中有type =“submit”时,我无法访问SaveDetailedInfo Action,导致ajax给我错误,但是当我删除type =“submit”时,ajax工作正常,但Save Action不执行.
请,任何想法如何执行两个操作?我以为也许在Ajax>成功尝试添加type = submit通过jquery并使用.click(),但对我来说听起来很奇怪.
解决方法
使用preventDefault()停止提交按钮的事件,并在ajax调用成功中使用submit()提交表单:
$('#btnSave').click(function (e) { e.preventDefault(); // <------------------ stop default behavIoUr of button var element = this; $.ajax({ url: "/Home/SaveDetailedInfo",success: function (data) { if (data.status == "Success") { alert("Done"); $(element).closest("form").submit(); //<------------ submit form } else { alert("Error occurs on the Database level!"); } },error: function () { alert("An error has occured!!!"); } }); });