简体   繁体   English

从jquery ajax内JS端的JsonResult获取属性

[英]Getting properties from JsonResult on the JS side inside jquery ajax

I am returning the following object JsonResult 我返回以下对象JsonResult

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

How do I get the error message out of it on the jquery side? 如何从jquery端获取错误消息?

this is my error delegate of jquery ajax 这是我的jquery ajax的错误委托

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

But it alerts as undefined. 但它警告未定义。 I tried result.Data as well as result.message....all undefined . 我尝试了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
            };
        }
    }
}

In my Controller I have an Action to test this 在我的控制器中,我有一个动作来测试

 [AjaxException]
    public ActionResult TestErrorHandling(string id)
    {
       if (string.IsNullOrEmpty(id))
        {
            throw new Exception("oh no");
        }
        return Json(new { success = true });
     }

In my js 在我的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);
    }

    });

Question: how do I get the errorMessage inside error delegate? 问题:如何在错误委托中获取errorMessage?

How do I get the error message out of it on the jquery side? 如何从jquery端获取错误消息?

Since you are returning a JSON object that comes with 200 status code the error callback will never be executed. 由于您返回的是带有200状态代码的JSON对象,因此永远不会执行错误回调。 So you could use the success callback in this case: 因此,在这种情况下,您可以使用success回调:

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

Or if you want the error handler to be executed make sure that you set the proper status code in your controller action: 或者,如果您希望执行错误处理程序,请确保在控制器操作中设置正确的状态代码:

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

and then: 接着:

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

You might also find the following answer useful. 您可能还会发现以下答案有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM