Skip to content

Instantly share code, notes, and snippets.

@bjcull
Created July 14, 2014 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjcull/ea63c086afc575912386 to your computer and use it in GitHub Desktop.
Save bjcull/ea63c086afc575912386 to your computer and use it in GitHub Desktop.
Return ModelState errors gracefully to an AJAX request
protected ActionResult JsonFormResponse(JsonRequestBehavior jsonRequestBehaviour = JsonRequestBehavior.DenyGet)
{
if (ModelState.IsValid)
{
return new HttpStatusCodeResult(200);
}
var errorList = new List<JsonValidationError>();
foreach (var key in ModelState.Keys)
{
ModelState modelState = null;
if (ModelState.TryGetValue(key, out modelState))
{
foreach (var error in modelState.Errors)
{
errorList.Add(new JsonValidationError()
{
Key = key,
Message = error.ErrorMessage
});
}
}
}
var response = new JsonResponse()
{
Type = "Validation",
Message = "",
Errors = errorList
};
Response.StatusCode = 400;
return Json(response, jsonRequestBehaviour);
}
public class JsonResponse
{
public string Type { get; set; }
public string Message { get; set; }
public IEnumerable<JsonValidationError> Errors { get; set; }
public JsonResponse()
{
Errors = new List<JsonValidationError>();
}
}
public class JsonValidationError
{
public string Key { get; set; }
public string Message { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment