当发生错误时,我的 OnException() 会被触发,并且错误会从我的 ajax 调用中正确记录。
问题是我在 Json 结果中返回的错误消息未显示,并且 result.data 为“”。
你能看出我的代码做错了什么吗?
$.post("/Admin/CreateOrganization", createOrganizationModel)
.done(function (data) {
if (data.success) {
//Everything is good
}
else {
swal(
'Failed to create organization.',
data.errorMessage,
'error'
);
}
})
.fail(function () {
swal(
'Failed to create organization. Please reload and try again',
'',
'error'
);
});
这是我的 OnException:
protected override void OnException(ExceptionContext filterContext)
{
// Log to database...
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, errorMessage = "An error has occurred." },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
base.OnException(filterContext);
}
else
{
Server.ClearError();
RedirectToErrorView();
}
}
最佳答案
答案:
我在发布这个问题时修复了它。
我的数据中有“错误”= ...而不是“errorMessage”
它现在在我的甜蜜警报消息框中显示错误消息。
关于c# - MVC OnException 返回 Json 结果以显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54947405/