jquery - 在 jquery ajax 中从 JS 端的 JsonResult 获取属性

标签 jquery asp.net-mvc json

我返回以下对象 JsonResult

return new JsonResult
            {
                Data = new { ErrorMessage = message },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };

如何在 jquery 端从中获取错误消息?

这是我的 jquery ajax 错误委托(delegate)

error: function (result) {
        alert('error');
        alert(result.ErrorMessage);
    }

但它警告为未定义。我尝试了 result.Data 以及 result.message....全部未定义

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
            };
        }
    }
}

在我的 Controller 中,我有一个操作来测试它

 [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);
    }

    });

问题:如何在错误委托(delegate)中获取 errorMessage?

最佳答案

How do I get the error message out of it on the jquery side?

由于您返回的是带有 200 状态代码的 JSON 对象,因此错误回调将永远不会被执行。因此,在这种情况下您可以使用 success 回调:

success: function(result) {
    if (result.ErrorMessage) {
        alert('some error occurred: ' + result.ErrorMessage);
    }
}

或者,如果您希望执行错误处理程序,请确保在 Controller 操作中设置正确的状态代码:

public ActionResult Foo()
{
    Response.StatusCode = 500;
    return Json(new { ErrorMessage = message });
}

然后:

error: function (jqXHR) {
    var result = $.parseJSON(jqXHR.responseText);
    alert('some error occurred: ' + result.ErrorMessage);
}

您可能还会找到following answer有用。

关于jquery - 在 jquery ajax 中从 JS 端的 JsonResult 获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249479/

相关文章:

javascript - jquery 加载函数在 chrome 中不起作用,而在 firefox 中起作用?

c# - 在 Razor 中将 css 与 c# mvc 混合

php - 将 AJAX JSON 与 PHP/MySQL 结合起来? php ://input?

javascript - firefox 中的 val() 设置了错误的值,删除了一个空格

javascript - 通过id属性的部分值获取div

javascript - PHP post提交未提交

c# - 如何解决 ASP.NET MVC Kendo UI 网格中的 CRUD 操作问题

c# - 传入字典的模型项在 ASP.net MVC 中属于“System.Collections.Generic.List...”类型

java - 使用id查找元素获取信息并添加到数组android java

javascript - 如何在 JavaScript 中附加到 json 对象