Serializing ModelState errors in a json call

Share on facebook
Share on twitter
Share on linkedin

In 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:

public ActionResult Create(ProjectModel model) 
    // Validation Errors 
        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.

More to explore