I used to confuse about ModelState in MVC. I begin to realize that there are two ModelState concepts often referenced in MVC discussion.

Most people know the first concept of ModelState, Controller.ModelState, which is a property of System.Web.Mvc.Controller. I am going to use Controller.ModelState property here to avoid any confusion.  Controller.ModelState property represents the model state dictionary object  (ModelStateDictionary) that contains the state of the model and of model-binding. The important properties of ModelStateDictionary  are:

  • Count. Gets the number of key/value pairs in the collection.
  • IsValid. Gets a value that indicates whether this instance of the model-state dictionary is valid.
  • Keys. Gets a collection that contains the keys in the dictionary.
  • Values. Gets a collection that contains the values in the dictionary.
One of ModelStateDictionary properties, Values, is particularly interesting. It basically is a collection that contains the values of the model-state dictionary.
public ICollection Values { get; }

Type: System.Collections.Generic.ICollection<ModelState>

You are right. ModelState is the type of objects in the collection, not the property of controller. It confused me years ago, and most people like me might never pay attention to.

Here comes the second concept of ModelState, which is from System.Web.Mvc.ModelState. There are only two properties in this class, Errors and Value.

  • Errors. Returns a ModelErrorCollection object that contains any errors that occurred during model binding.
  • Value. Returns a ValueProviderResult object that encapsulates the value that was being bound during model binding.

If we organize our thinking a little bit, here is the structure for easy memorization.