简体   繁体   English

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

[英]How to call MVC Action using Jquery AJAX and then submit form in MVC?

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给我error ,但当我删除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() ,但这听起来很奇怪。

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!!!");
        }
    });
});

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening ie Your AJAX call is made in addition to the form submission; 假设您的按钮位于表单中,则不会阻止按钮单击的默认行为发生,即除了表单提交之外还进行了您的AJAX调用; what you're very likely seeing is one of 你很可能看到的是其中之一

  1. the form submission happens faster than the AJAX call returns 表单提交的速度比AJAX调用返回的速度快
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form. 表单提交导致浏览器中止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!!!");
        }
    });
});

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM