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
resultvariable 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.
which could be registered as a global action filter:
and on the client you could also have a global AJAX error handler for all AJAX requests on the same page: