在 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/