c# - 错误时的 ASP MVC 和 JsonResult

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

在 ASP MVC 中,我有一个返回 json 数据的 Controller :

public JsonResult Edit(int? id)
{
   if(id==null)
   {
      Response.StatusCode = (int)HttpStatusCode.BadRequest;
      return Json(new { message = "Bad Request" }, JsonRequestBehavior.AllowGet);
   }

   car carTmp = db.car.Find(id);
   if (carTmp == null)
   {
      Response.StatusCode = (int)HttpStatusCode.NotFound;
      return Json(new { message = "Not Found" }, JsonRequestBehavior.AllowGet);
   }

   return Json(carTmp, JsonRequestBehavior.AllowGet);
}

我还有以下 ajax 请求:

$.getJSON("Edit/" + data, function (result) {
            var car = result;
        })
        .error(function (error) {
            alert(error.message);
        })

为什么在成功的情况下,在结果对象中我有 json 对象(即:我可以访问 result.id、result.name ecc...)但在错误的情况下,error.message 是未定义的? (我把消息放到error.responseJson.message)

最佳答案

您将响应中的状态代码设置为 404,因此应执行错误回调。

问题是 error callback被定义为 function( jqXHR, textStatus, errorThrown ),其中 jqxhr将有一个 responseJSON 属性。

您只需将代码更改为:

$.getJSON("Edit/" + data, function (result) {
    var car = result;
})
.error(function (xhr) {
    alert(xhr.responseJSON.message);
})

关于c# - 错误时的 ASP MVC 和 JsonResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33564979/

相关文章:

c# - 如何对 IEnumerable<string> 进行排序

c# - 在二叉搜索树 C# 中查找节点值

.net - 将 EF6 连接到 Oracle 11g DB 时不会显示数据源名称

c# - 堆栈面板的水平滚动不起作用

c# - 使用 C# 从文本文件中删除交替行

asp.net - 应该在哪个项目层筛选 DTO 的存在?

c# - 当编写ASPX时,在aspx本身中使用html是不明智的吗?

c# - 使用 GetAll() 和 GetByIds(int[] ids) 发现 Web API 多个操作

c# - 如何检查数据库中是否存在记录 - 最快的方法

c# - 如何在不读取的情况下检查 xml 中是否存在另一个节点 - C#