stej
stej

Reputation: 29479

How should asp.net(mvc) server return error to jquery ajax call to be caught in error callback?

Suppose I have a method in my controller that is called via a jQuery AJAX call. E.g. I'd like to delete a user. When everything goes fine, I return new Content('ok') and exit the method.

What should I do when an error occured? I'd like to indicate it by an appropriate status code, so that my error call back would be called called. Why status code? Read here: How do you trigger the "error" callback in a jQuery AJAX call using ASP.NET MVC?

However, the approach doesn't work because IIS7 returns it's own message (Bad request) insted of my custom error message.

Besides that there are two other catches:

  1. It has to work with IIS6 as well
  2. IE8 doesn't return the 'Bad request' string. Inside error callback the property request.responseTest is null.

The error callback could look like this: error: function(request) { alert(request.responseText);}

Upvotes: 26

Views: 9893

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126587

Setting the Response.StatusCode is the correct thing to do. To fix IIS's "helpful" error handling, set the HttpResponse.TrySkipIisCustomErrors property. You can read more about this here.

Upvotes: 30

Related Questions