Validating Models

The MVC framework automatically performs some basic validation when it performs model binding. In this section, I'll show you what we get built in and how we can add to that to perform more sophisticated validation.

Setting Up Basic Model Validation

The Age property in the Registration class is defined as an int, and during the model binding process, the MVC framework has to convert the string value that has been provided in the request. If the request value cannot be converted to an int, then the model is classified as invalid.

To detect and handle invalid models, we need to make some enhancements to our controller and view. Listing 29-9 shows the changes to the RegistrationController class.

Listing 29-9. Enhancing the controller ...

Get Applied ASP.NET 4 in Context now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.