【问题标题】:MVC ajax call how to handle error responsesMVC ajax 调用如何处理错误响应
【发布时间】:2014-02-24 05:22:29
【问题描述】:

我有一个关于 ajax 调用的问题:这是我的 ajax 调用:

$.ajax({
    url: "/Article/DeleteArticle/"+id,
    type: "GET",
    error: function (response) {

    },
    success: function (response) {

    }
});

这是我的控制器:

public ActionResult DeletePicture(int id)
{
    bool success = Operations.DeleteArticle(id);
    return null;
}

我想知道我应该返回什么来获得内部错误?这个错误函数基本上是在什么时候被调用的?如果服务器或..发生错误?

关于成功我怎样才能传递一些数据?

现实生活中的例子:

想象一下我调用这个 ajax 方法来删​​除一篇文章,当它被删除时,我想显示一些成功消息。如果它失败了,那么在我的操作中我会得到success=false,我想显示一些其他消息,例如:失败。

如何实现?

【问题讨论】:

  • 创建一个 json 对象并从 Action 中返回它。相应地在回调中处理
  • 发生超时或操作不存在时,会发生错误。但是删除成功或删除失败可以在你的成功部分成功处理

标签: c# asp.net ajax asp.net-mvc asp.net-mvc-5


【解决方案1】:

您可以通过创建一个表示响应的对象来处理您的 Ajax 调用:

public class AjaxResponse
{
        public bool Success { get; set; }
        public string Message { get; set; }
    }
}

然后返回如下:

public ActionResult DeletePicture(int id)
{
    // success failed by default
    var response = new AjaxResponse { Success = false };
    try 
    {
     bool success = Operations.DeleteArticle(id);
     response.Success = success;
     // Set a message for UI
     response.Message = success ? "Success" : "Failed";
     }
     catch
     {
      // handle exception
      // return the response with success false
      return Json(response, JsonRequestBehavior.AllowGet);
     }
     return Json(response, JsonRequestBehavior.AllowGet);
}

然后您可以传递数据并按如下方式处理它:

$.ajax({
    url: "/Article/DeleteArticle/",
    type: "GET",
    data : { Id : id },
    dataType: 'json',
    error: function (response) {

    // Handle error from response.Success or response.Message

    },
    success: function (response) {

        // Handle error from response.Success or response.Message

    }
});

句柄错误可以简单地将消息显示回 HTML 元素或弹出某种 javascript 通知。

【讨论】:

  • 如果您的 ajax 调用抛出错误,则会调用错误,您也可以在您的操作周围放置一个 try catch。我将在上面更新它以显示这一点。
  • 现在为您更新。 :)
  • 非常适合单人通话。但是,在链接 Deferreds 时这很糟糕,因为除非您手动处理每个 Deferreds,否则其他人会错误地触发。这会使你的有效载荷膨胀。
【解决方案2】:

你可以使用它

public ActionResult DeleteArticle(int id)
{
    bool success = Operations.DeleteArticle(id);       

    return Json(success, JsonRequestBehavior.AllowGet);
}


$.ajax({
    url: "/Article/DeleteArticle/",
    type: "GET",
    data : { Id : id },
    dataType: 'json',
    error: function (response) {    
       if(response!=null && response.length!=0)
       {
         alert('error');
       }    
    },
    success: function (response) {  
       if(response) {
         alert('Success');
       }   
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-20
    • 2016-01-24
    • 2012-09-12
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多