Validation and Model State Relation in MVC

The primary side effect of model binding is model state (accessible in a Controller-derived object using the ModelState property). Not only does model state contain all the values a user attempted to put into model properties, but model state also contains all the errors associated with each property (and any errors associated with the model object itself). If there are any errors in modelstate, ModelState.IsValid returns false.
As an example, imagine the user submits the checkout page without providing a value for LastName. With the Required validation annotation in place, all the following expressions will return true after model binding occurs:

ModelState.IsValid == false
ModelState.IsValidField("LastName") == false
ModelState["LastName"].Errors.Count > 0

You can also look in model state to see the error message associated with the failed validation:

var lastNameErrorMessage = ModelState["LastName"].Errors[0].ErrorMessage;

Of course, you rarely need to write code to look for specific error messages. Just as the runtime automatically feeds validation errors into model state, it can also automatically pull errors out of model state. As discussed in Chapter 5, the built-in HTML helpers use model state (and the presence of errors in model state) to change the display of the model in a view. For example, the ValidationMessage helper displays error messages associated with a particular piece of view data by looking at model state.

@Html.ValidationMessageFor(m => m.LastName)

The only question a controller action generally needs to ask is this: Is the model state valid or not?

Tagged . Bookmark the permalink.

Leave a Reply