BLOG
Serializing ModelState errors in a json call
In ASP.net MVC, the ModelStateDictionary class contains all of the validation errors for your models that get posted from your forms. The HTML helpers Html.ValidationSummary and Html.ValidationMessageFor will look at the Model State to display these validation messages. When you are submitting your form with an AJAX request and return a JSON response, then you need to have a way to return these validation errors to your views. Here is a helpful extension method that will allow you to do that:
public static class ModelStateExtensions
{
public static IDictionary ToSerializedDictionary(this ModelStateDictionary modelState)
{ return modelState.ToDictionary(
k => k.Key,
v => v.Value.Errors.Select(x => x.ErrorMessage).ToArray()
);
}
}
Now in your controller action you can return this data back to your view:
[HttpPost] public ActionResult Create(ProjectModel model)
{
// Validation Errors
if(!ModelState.IsValid)
{
return Json(ModelState.ToSerializedDictionary());
}
// Success - Save Project data
}
In your view you can now write some javascript code to display the errors in your view.