如何使用jQuery AJAX调用MVC操作,然后在MVC提交表单?

问题描述:

在我的MVC视图我有按钮:

On my MVC View I have button:

<input id="btnSave" type="submit" name="Save" value="Save" />

当我点击这个按钮,我需要的一个电话行动,做一些东西那里,然后提交我的形式。

When I click this button I need call one Action, do some stuff there and then Submit my form.

我有这个jQuery的:

I have this 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个动作:

Then I want to submit my form. In Controller I have 2 Actions:

public ActionResult SaveDetailedInfo(Option[] Options)
{
    return Json(new { status = "Success", message = "Success" });
}

[HttpPost]
public ActionResult Save()
{ 
    return RedirectToAction("Index", "Home");
}

现在的问题是,当我有 TYPE =提交在我的按钮,我不能达到 SaveDetailedInfo 行动,导致阿贾克斯给了我错误,但是当我删除 TYPE =提交,AJAX的工作正常,但保存行动从来没有执行。

The problem is when I have type="submit" in my button, I can't reach SaveDetailedInfo Action, cause ajax gives me error, but when I remove type="submit", ajax works fine, but Save Action never executes.

请,任何想法如何执行这两种操作?我想,也许阿贾克斯&GT后;成功尝试添加键入=提交通过jQuery和使用。点击(),但这听起来很奇怪,我。

Please, any ideas how to execute both Actions? I thought maybe after Ajax > Success try to add type=submit through jquery and use .click(), but it sounds strange to me.

使用 preventDefault()停止提交按钮,并在Ajax调用成功提交事件使用格式提交()

Use preventDefault() to stop the event of submit button and in ajax call success submit the form using submit():

$('#btnSave').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;    
    $.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");
                $(element).closest("form").submit(); //<------------ submit form
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});