Jquery – How to trigger the “error” callback in a jQuery AJAX call using ASP.NET MVC

ajaxasp.net-mvcjquery

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) {

   }
 });

Best Answer

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.