Organizing and Using Validation Attributes
Introduction
Welcome to the final lesson of this course on binding and validating data in Razor Pages. In the previous lessons, we covered the basics of data binding and validation, explored advanced data binding techniques, and learned how to validate data to ensure its integrity.
In this lesson, we will focus on combining things altogether and building a full application using the techniques that we've learned. Let's dive in!
Implementing Validation Attributes in the User Model
Let's apply these validation attributes to our User model. The User model will include validation for Name and Age.
User.cs
In this code:
- The
[Required]attribute on theNameproperty ensures that the name is not left empty, displaying an error message if it is. - The
[Range]attribute on theAgeproperty ensures the age is between 18 and 100; otherwise, an error message will be shown.
Binding Data with BindProperty
As a quick reminder, the [BindProperty] attribute is used to bind form input data to model properties. In our previous lessons, we looked at how to use this attribute to link form data to model properties.
Let's see how we bind data to the UserProfileModel class using the [BindProperty] attribute:
UserProfile.cshtml.cs
Here:
- The
[BindProperty]attribute is used to bind form input data to theUserInputproperty. - The
OnGet()method initializes theUserInputwith default values. - The
OnPost()method handles the form submission and checks if the model state is valid before proceeding with the save logic.
