【问题标题】:JQuery AJAX Success With Multiple MVC Controller Methods使用多个 MVC 控制器方法的 JQuery AJAX 成功
【发布时间】:2015-06-04 15:58:57
【问题描述】:

假设我将一个表单发布到一个 MVC 控制器和这样的操作

function ajaxFunction() {        
    $.ajax({
        type: "POST",
        url: "ControllerName/FirstMethod",
        data: $('#form').serialize(),
        success: function () {
            //I'm wondering if this gets run after the FirstMethod or SecondMethod   
        }
    });
)

控制器动作做了一些事情,然后像这样重定向到下一个方法

[HttpPost]
public ActionResult FirstMethod()
{
    //Some code run here

    //Send to the next method
    return RedirectToAction("SecondMethod");
}

public void SecondMethod()
{
    //Something else done here
}

所以整个过程就是先post到FirstMethod,然后运行SecondMethod。我的问题是 - Ajax success() 方法何时运行?是在 FirstMethod 之后还是 SecondMethod 之后?

【问题讨论】:

    标签: jquery ajax asp.net-mvc controller


    【解决方案1】:

    RedirectToAction 返回 302 的 HTTP 状态代码,这使得 AJAX 对重定向 URL (SecondMethod) 执行 GET。

    只有在返回 2XX HTTP 代码时才会调用 jQuery AJAX 成功。如果 SecondMethod 返回带有 2XX 状态代码的东西(例如视图),那么它将是。否则,它永远不会被调用。

    【讨论】:

    • 这很有趣。感谢您的回复。但是,当您直接调用公共 void 方法时会发生什么?我的代码中有一些,我正在使用 ajax 成功函数。这是另一种情况吗?
    • 当重定向到返回 void 的操作方法时,MVC 实际上会返回一个 EmptyResult,它是一个 200 状态码,因此它确实会运行 success() 回调。否则,它取决于 ActionResult 类型。大多数返回 2XX 代码,但 HttpNotFoundResult、HttpUnauthorizedResult、HttpStatusCodeResult 除外。
    猜你喜欢
    • 1970-01-01
    • 2016-06-03
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多