0

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?

2 Answers 2

2

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

How to you throw the exception? I tried [HttpPost] [AjaxErrorHandler] public ActionResult LogOn(LogOnModel model, string returnUrl) { //some code if(blabla) throw new Exception("blaBla"); } But it did not work.
I tried with Ajax.BeginForm instead of Html.BeginForm. The exception goes through the AjaxErrorHandler, but the global Ajax error handler on the client does not show the message.
0
$.ajax({
    url: "/Account/LogOn",
    type: "POST",
    dataType: "json",
    data: form.serialize(),
    success: function (result) {
        alert(result);     
    }
    error: function (req, status, error) {
        //your logic
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.