简体   繁体   中英

jQuery parsing JSON results returned from controllers

I want to parse JSON results, containing status or error messages, returned from controller method or custom exception filter and display the messages.

     $.ajax({
        url: "/Account/LogOn",
        type: "POST",
        dataType: "json",
        data: form.serialize(),
        success: function (result) {
            alert(result);     
        }
    });

I think that with this code I can do it for a specific Action Result or method. Is there a way to do this for every JSON result returned to the page?

No, there's no way to do this for every possible JSON returned by your controller actions because the structure will be different and the properties of this result variable won't be the same.

The correct way would be to have a custom error handler which will intercept all exceptions and wrap them in a well defined JSON structure. Then you could use the error callback in the AJAX request to handle this case.

public class AjaxErrorHandler : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new JsonResult
            {
                Data = new
                {
                    ErrorMessage = filterContext.Exception.Message
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
}

which could be registered as a global action filter:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new AjaxErrorHandlerAttribute());
}

and on the client you could also have a global AJAX error handler for all AJAX requests on the same page:

$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    var json = $.parseJSON(jqXHR.response);
    alert(json.ErrorMessage);
});
$.ajax({
    url: "/Account/LogOn",
    type: "POST",
    dataType: "json",
    data: form.serialize(),
    success: function (result) {
        alert(result);     
    }
    error: function (req, status, error) {
        //your logic
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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