I am using AjaxSubmit to post a form and there are server side validations done using XVal (RuleException way). I am not using the try/catch way to add error to Model and then send to view. Instead - I want to use the HandleError attibute and in the OnException I am adding the errors to Model. The major problem is how do I get those errors as a results in the Ajax Call?
There is not a great solution built in right now. Doing this correctly requires a client-side validation framework (because, to display the errors, you need to dynamically change the HTML page), and until recently, ASP.NET MVC has not had that. However, ASP.NET MVC 2 Preview 2 introduced client-side validation, so it's reasonable to presume that something might be built into the framework soon.
In the meantime, however, HandleErrorAttribute won't help you. HandleErrorAttribute only knows how to redirect to an error page, which is generally not what you want to do in response to a server-side validation error even with a "normal" POST, and certainly not with an AJAX post.
There really two different scenarios you need to handle:
- Validation errors are not catastrophic failures; they are simply bad user data, which you should expect. You just need to get the information back to the page, so that the page can be marked up to tell the user how to fix their data.
- You also need to handle catastrophic failures, like unanticipated exceptions. This is akin to what HandleErrorAttribute does, insofar as you can display a message to a user, but you cannot necessarily match that message up with specific fields on your page.
To handle the first scenario of error, you need to wrap the model state up into an object which will be parsable in JavaScript code; JSON is the obvious fit here. You then need to have JavaScript code on the client side which parses this object and marks up the form fields. This is easier if you tie into an existing client-side validation framework, which already contains code for marking up form fields.
To handle the second type of error, you can extend HandleErrorAttribute in order to provide JSON instead of HTML in the event of a catastrophic failure. Again, you will need to write JavaScript code that will be executed in the event of a failure -- jQuery's global ajaxError
event is useful here -- that detects this structured error information you've created and display some sort of useful message to the user.
If all this sounds a bit involved, well, it is, which is why it may make more sense to wait and see what will be built-in when MVC 2 is finally released.