Kevin Pang
Kevin Pang

Reputation: 41442

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

   }
 });

Upvotes: 31

Views: 25847

Answers (6)

Adam Lassek
Adam Lassek

Reputation: 35505

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.

Upvotes: 22

Rodrigo Perez Burgues
Rodrigo Perez Burgues

Reputation: 248

I send you a proposal; works with contrelled and uncontrolled exceptions.

  public class CodeExceptionToHttpFilter : FilterAttribute, IExceptionFilter
{
    public CodeExceptionToHttpFilter()
    {
      Order = 2;
    }
    public void OnException(ExceptionContext filterContext)
    {
      var codeException = filterContext.Exception as CodeException;
      var response = filterContext.RequestContext.HttpContext.Response;
  response.StatusCode = (codeException == null)? 550: 551;
      response.ContentType = MediaTypeNames.Text.Plain;
      response.Charset = "utf-8";
      response.Write(filter.Exception.Message);
      filterContext.ExceptionHandled = true;
      response.TrySkipIisCustomErrors = true;
   }

}

More info on my blog. http://rodrigopb.wordpress.com/2012/11/28/gestion-de-errores-en-peticiones-ajax-a-mvc/

Upvotes: 1

Derek Morrison
Derek Morrison

Reputation: 5574

If you're using MVC 3, then you can return an ActionResult in your controller that has the HTTP status code and status message together:

return new HttpStatusCodeResult(500, "Error message");

Then, in your error callback:

error: function (request, textStatus, errorThrown) {
    alert(request.statusText);
}

Upvotes: 8

Todd Smith
Todd Smith

Reputation: 17272

If you're using

[HandleError]

then throwing a HttpException is going to get caught and routed to your custom error page.

Another option is to use

Response.StatusCode = 500;
Response.Write("Error Message");
Response.End();

There's probably a more convenient way to write this but I haven't stumbled upon it yet.

Upvotes: 8

John Sheehan
John Sheehan

Reputation: 78104

I think that event is raised for any response that has a response code other than 200. I can't find proof of this in the docs though.

To do this from code (works in Webforms):

throw new HttpException(500, "Error message");

Upvotes: 1

Salty
Salty

Reputation: 6688

According to this page, you just need to apply the header HTTP/1.0 500 Internal Server Error on your ASP.net page. The $.ajax request will catch that error and execute the error callback function. =]

Upvotes: 1

Related Questions