Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?
For example, if I want to throw an exception on the server side v
This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:
ModelStateException
that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)HandleModelStateExceptionAttribute
that catches custom exception and returns HTTP error status with model state error in the bodyThis provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success
and error
handlers.
$.ajax({
type: "POST",
url: "some/url",
success: function(data, status, xhr) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
[HandleModelStateException]
public ActionResult Create(User user)
{
if (!this.ModelState.IsValid)
{
throw new ModelStateException(this.ModelState);
}
// create new user because validation was successful
}
The whole problem is detailed in this blog post where you can find all the code to run this in your application.