如何使用Jquery AJAX调用MVC Action,然后在MVC中提交表单?

时间:2022-11-23 14:11:00

On my MVC View I have button:

在我的MVC视图中我有按钮:

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

当我点击这个按钮时,我需要调用一个动作,在那里做一些事情,然后提交我的表格。

I have this jQuery:

我有这个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!!!");
        }
    });
});

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

然后我想提交我的表格。在Controller我有2个动作:

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

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

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.

问题是当我在我的按钮中输入type =“submit”时,我无法访问SaveDetailedInfo Action,导致ajax给我错误,但当我删除type =“submit”时,ajax工作正常,但Save Action永远不会执行。

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.

请问,如何执行这两项操作?我想也许在Ajax> Success之后尝试通过jquery添加type = submit并使用.click(),但这对我来说听起来很奇怪。

3 个解决方案

#1


20  

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

使用preventDefault()来停止提交按钮的事件,并在ajax调用成功中使用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!!!");
        }
    });
});

#2


5  

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

假设您的按钮位于表单中,则不会阻止按钮单击的默认行为发生,即除了表单提交之外还进行了您的AJAX调用;你很可能看到的是其中之一

  1. the form submission happens faster than the AJAX call returns
  2. 表单提交的速度比AJAX调用返回的速度快
  3. the form submission causes the browser to abort the AJAX request and continues with submitting the form.
  4. 表单提交导致浏览器中止AJAX请求并继续提交表单。

So you should prevent the default behaviour of the button click

因此,您应该阻止按钮单击的默认行为

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

#3


2  

Your C# action "Save" doesn't execute because your AJAX url is pointing to "/Home/SaveDetailedInfo" and not "/Home/Save".

您的C#操作“保存”不会执行,因为您的AJAX网址指向“/ Home / SaveDetailedInfo”而不是“/ Home / Save”。

To call another action from within an action you can maybe try this solution: link

要从操作中调用另一个操作,您可以尝试此解决方案:链接

Here's another better solution : link

这是另一个更好的解决方案:链接

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

[HttpPost]
public ActionResult Save()
{ 
    return RedirectToAction("SaveDetailedInfo", Options);
}

AJAX:

AJAX:

Initial ajax call url: "/Home/Save"
on success callback: 
   make new ajax url: "/Home/SaveDetailedInfo"

#1


20  

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

使用preventDefault()来停止提交按钮的事件,并在ajax调用成功中使用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!!!");
        }
    });
});

#2


5  

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

假设您的按钮位于表单中,则不会阻止按钮单击的默认行为发生,即除了表单提交之外还进行了您的AJAX调用;你很可能看到的是其中之一

  1. the form submission happens faster than the AJAX call returns
  2. 表单提交的速度比AJAX调用返回的速度快
  3. the form submission causes the browser to abort the AJAX request and continues with submitting the form.
  4. 表单提交导致浏览器中止AJAX请求并继续提交表单。

So you should prevent the default behaviour of the button click

因此,您应该阻止按钮单击的默认行为

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

#3


2  

Your C# action "Save" doesn't execute because your AJAX url is pointing to "/Home/SaveDetailedInfo" and not "/Home/Save".

您的C#操作“保存”不会执行,因为您的AJAX网址指向“/ Home / SaveDetailedInfo”而不是“/ Home / Save”。

To call another action from within an action you can maybe try this solution: link

要从操作中调用另一个操作,您可以尝试此解决方案:链接

Here's another better solution : link

这是另一个更好的解决方案:链接

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

[HttpPost]
public ActionResult Save()
{ 
    return RedirectToAction("SaveDetailedInfo", Options);
}

AJAX:

AJAX:

Initial ajax call url: "/Home/Save"
on success callback: 
   make new ajax url: "/Home/SaveDetailedInfo"