Created
July 14, 2014 04:29
-
-
Save bjcull/ea63c086afc575912386 to your computer and use it in GitHub Desktop.
Return ModelState errors gracefully to an AJAX request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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