This is related to my question on how to handle errors from jQuery AJAX calls. Several responses suggested that I use the "error" callback to display any errors from a jQuery AJAX call. I was wondering how to do that using ASP.NET MVC. Is there a way for my controller action to return an error that would be accessible from the "error" callback? The client side code would look something like this:
$.ajax({ type: "POST", url: "MyUrl", data: "val1=test", success: function(result){ // Do stuff }, error: function(request,status,errorThrown) { } });
version added: 1.0.Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the . ajaxError() method are executed at this time.
The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.
NOTE: Hey, this was posted before ASP.Net MVC even hit 1.0, and I haven't even looked at the framework since then. You should probably stop upvoting this.
Do something like this:
Response.StatusCode = (int)HttpStatusCode.BadRequest; actionResult = this.Content("Error message here");
The status code should change depending on the nature of the error; generally, 4xx for user-generated problems and 5xx for server-side problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With