Normally, when you used HttpPost/Form submission to post the view through the controller then you can have the model validation applied automatically through @Html.ValidationSummary()
But how do you get the ModelState errors through Json? You can still use LINQ to get the model errors from the ModelState and pass it through JSON
Code Snippet
- public ActionResult JsonRegister(MemberModel.RegistrationModel model)
- {
- string error = string.Empty;
- if (!ModelState.IsValid)
- {
- IEnumerable<System.Web.Mvc.ModelError> modelerrors = ModelState.SelectMany(x => x.Value.Errors);
- foreach (var modelerror in modelerrors)
- {
- error += modelerror.ErrorMessage + “\n”;
- }
- }
- return Json(new { success = false, errors = error }, JsonRequestBehavior.AllowGet);
- }
Leave a Reply