return Json error from ASP.NET MVC

would be nicer to return a list of errors and then build the html at the client.

Response.StatusCode = (int)HttpStatusCode.BadRequest;
List<string> errors = new List<string>();
//..some processing
errors.Add("Error 1");
//..some processing
errors.Add("Error 2");
return Json(errors);

and then at the client side

 .ajax({...
    error: function(xhr, textStatus, exceptionThrown) {
      var errorData = $.parseJSON(xhr.responseText);
      var errorMessages = [];
      //this ugly loop is because List<> is serialized to an object instead of an array
      for (var key in errorData)
      {
         errorMessages.push(errorData[key]);
      }
       $('#result').html(errorMessages.join("<br />"));
  },

you can also return a more specific error object and use a template solution, but this is the idea

Leave a Comment