【发布时间】:2011-11-23 21:43:51
【问题描述】:
我正在返回以下对象 JsonResult
return new JsonResult
{
Data = new { ErrorMessage = message },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
如何在 jquery 端获取错误消息?
这是我的 jquery ajax 错误委托
error: function (result) {
alert('error');
alert(result.ErrorMessage);
}
但它警告为未定义。我试过result.Data 以及result.message....所有undefined。
namespace myApp.ActionFilters
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class AjaxException : ActionFilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest()) return;
filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
//Let the system know that the exception has been handled
filterContext.ExceptionHandled = true;
}
protected JsonResult AjaxError(string message, ExceptionContext filterContext)
{
//If message is null or empty, then fill with generic message
if (String.IsNullOrEmpty(message))
message = "Something went wrong while processing your request. Please refresh the page and try again.";
//Set the response status code to 500
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
//Needed for IIS7.0
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
return new JsonResult
{
Data = new { ErrorMessage = message },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
}
}
在我的控制器中,我有一个动作来测试这个
[AjaxException]
public ActionResult TestErrorHandling(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
在我的 js 中
id = "";
$.ajax({
contentType: 'application/json, charset=utf-8',
type: "POST",
url: "/Controller/TestErrorHandling",
data: JSON.stringify({ id: id }),
cache: false,
dataType: "json",
success: function (result) {
alert('some error occurred: ' + result.ErrorMessage);
alert('success!');
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error');
alert(xhr.ErrorMessage);
}
});
问题:如何在错误委托中获取 errorMessage?
【问题讨论】:
-
您的代码的第一部分似乎在语法上无效。构造函数的参数应该总是用单括号括起来,而不是花括号。此外,在 new 关键字之后必须始终是函数,而不是对象。希望对您有所帮助。
-
@Betamos,您可能应该阅读 C# 中的对象和集合初始化器语法:msdn.microsoft.com/en-us/library/bb384062.aspx
-
@DarinDimitrov 哦,哈哈。对不起。以为都是JS。请忽略我之前的评论。
-
@Betamos,哦不,这根本不是你的错。正确标记他的问题并将其置于上下文中是 OP 的错。他甚至没有提到他最初使用的是 asp.net-mvc,这可能完全解释了人们的困惑。他用 javascript 和 jquery 标记它,显然他展示的代码对 javascript 没有任何意义。
标签: jquery asp.net-mvc json