3

I'm new to JSON and have been using it with MVC3 ASP.NET but could somebody shed some light on how to return an error per a JSON result?

I have the following call from my View:

  $.ajax({
     type: "POST",
     dataType: "json",
     url: "EditJSON",
     data: { FilmID: InputFilmID, Title: InputTitle, Description: InputDescription},
     success: function (result) {
        alert(result.Message + " updating film " + result.Title);
        window.location = "../All";
     },
     error: function (error) {
        alert('error');
     }
  });

Controller handles the request as a success. What would I pass back for a JSON error so that the error: function handled back at the View?

    [AcceptVerbs("POST")]
    public JsonResult EditJSON(BobsMoviesMVC2.Models.Film film)
    {
       filmRepository.Update(film);
       return Json(new {Message = "Success", Title = film.Title });

       // What would I return for an error here?
    }    

Thanks!

Mariah
  • 727
  • 5
  • 12
  • 25

3 Answers3

11

jQuery uses the HTTP response code to determine success or failure.

HTTP response codes >= 400 are considered errors. HTTP response codes >= 200 and < 400 are considered successes.

Return appropriate HTTP codes from your server-side code to get the behavior you're after.

Luke Sneeringer
  • 9,270
  • 2
  • 35
  • 32
  • 1
    So, I would have to just add, Response.StatusCode = (int)HttpStatusCode.BadRequest; before returning my json result? – Mariah May 15 '11 at 18:44
  • I'm sorry, I don't know ASP.NET so I can't be certain what to do there. What you suggested looks plausible to me, though. – Luke Sneeringer May 15 '11 at 18:55
6

Confirmed, in .NET you can put:

Response.StatusCode = (int)HttpStatusCode.InternalServerError,

or whatever error status code you wish, right before your JSON return statement. (Thank you Mariah).

Check out the 'error' option of the jquery ajax call to see what you can do with the resulting error on the client-side.

Daniel Gill
  • 3,261
  • 2
  • 23
  • 21
0

A header with a status code other than 2xx or 3xx, probably a 5xx or 4xx error code.

Ry-
  • 218,210
  • 55
  • 464
  • 476