Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you trigger the "error" callback in a jQuery AJAX call using ASP.NET MVC?

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) {     }  }); 
like image 710
Kevin Pang Avatar asked Jan 02 '09 18:01

Kevin Pang


People also ask

What triggers jQuery Ajax fail?

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.

How do you handle errors in Ajax call?

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.


1 Answers

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.

like image 118
Adam Lassek Avatar answered Oct 07 '22 12:10

Adam Lassek