Scottingham
Scottingham

Reputation: 946

Returning an error to an AJAX call from a Controller in MVC3

I have an ajax call that looks like this:

  $.ajax({
                url: '@Url.Action("SaveStudy")',
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify({
                    ....irrelevant data
                }),
                success: function (result) {

                      ....irrelevant data

                },
                error: function (result) {

                    //alert("I had an error");
                }
            });

The error section of that ajax call is reached when logic in my controller sends back a HttpStatusCodeResult. The controller code looks like this:

 if (Participants==null)
            {
                return new HttpStatusCodeResult(409, "No Players were selected!");
            }

Is there a way to get that error message 'No Players were selected' to display in an alert (or anything, really) in the error section of my AJAX call?

Upvotes: 2

Views: 1902

Answers (1)

JasCav
JasCav

Reputation: 34632

Take a look at the jQuery.ajax documentation. As of jQuery 1.5, you can use statuscode to get that information.

$.ajax({
  statusCode: {
    404: function() {
      alert("page not found");
    }
  }
});

Upvotes: 4

Related Questions