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!
Let's apply these validation attributes to our User
model. The User
model will include validation for Name
and Age
.
User.cs
C#1using System.ComponentModel.DataAnnotations; 2 3public class User 4{ 5 [Required(ErrorMessage = "Name is required.")] 6 public string Name { get; set; } 7 8 [Range(18, 100, ErrorMessage = "Age must be between 18 and 100.")] 9 public int Age { get; set; } 10}
In this code:
[Required]
attribute on the Name
property ensures that the name is not left empty, displaying an error message if it is.[Range]
attribute on the Age
property ensures the age is between 18 and 100; otherwise, an error message will be shown.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
C#1using Microsoft.AspNetCore.Mvc; 2using Microsoft.AspNetCore.Mvc.RazorPages; 3 4public class UserProfileModel : PageModel 5{ 6 [BindProperty] 7 public User UserInput { get; set; } 8 9 public void OnGet() 10 { 11 UserInput = new User(); // Initialize with default values 12 } 13 14 public IActionResult OnPost() 15 { 16 if (!ModelState.IsValid) 17 { 18 ViewData["Message"] = "Input data is invalid, check it and try again."; 19 return Page(); 20 } 21 22 // Save user profile logic 23 24 ViewData["Message"] = "User profile saved successfully."; 25 return Page(); // Stay on the same page and display a success message 26 } 27}
Here:
[BindProperty]
attribute is used to bind form input data to the UserInput
property.OnGet()
method initializes the UserInput
with default values.OnPost()
method handles the form submission and checks if the model state is valid before proceeding with the save logic.To ensure that the input data meets the specified validation rules, we need to validate the form data on the server side. When the form is submitted, the server checks if the data is valid using ModelState.IsValid
.
If the data is not valid, we will display an error message to the user. Let's see how we implement this in our UserProfileModel
class.
UserProfile.cshtml.cs
C#1public IActionResult OnPost() 2{ 3 if (!ModelState.IsValid) 4 { 5 ViewData["Message"] = "Input data is invalid, check it and try again."; 6 return Page(); 7 } 8 9 // Save user profile logic 10 11 ViewData["Message"] = "User profile saved successfully."; 12 return Page(); 13}
In this method:
ModelState.IsValid
checks if the model has passed all validation rules.To provide user feedback when validation errors occur, we use the asp-validation-for
tag helper in Razor Pages. This tag helper automatically displays validation error messages associated with a specific model property.
Let's incorporate this into our UserProfile
page:
UserProfile.cshtml
HTML, XML1@page 2@model UserProfileModel 3<form method="post"> 4 <div> 5 <label asp-for="UserInput.Name">User Name</label> 6 <input asp-for="UserInput.Name" name="UserInput.Name" /> 7 <span asp-validation-for="UserInput.Name" class="text-danger"></span> 8 </div> 9 <div> 10 <label asp-for="UserInput.Age">Age</label> 11 <input asp-for="UserInput.Age" name="UserInput.Age" /> 12 <span asp-validation-for="UserInput.Age" class="text-danger"></span> 13 </div> 14 <button type="submit">Save</button> 15</form> 16 17@if (ViewData["Message"] != null) 18{ 19 <div class="alert"> 20 @ViewData["Message"] 21 </div> 22}
Here:
asp-validation-for
tag helper is used to display validation messages next to the form inputs.Let's put everything together and see how it all works:
Model (User.cs
)
User
model with validation attributes.Code-Behind (UserProfile.cshtml.cs
)
UserInput
property using [BindProperty]
.OnPost()
method and validate the data.ViewData
.View (UserProfile.cshtml
)
Name
and Age
.asp-validation-for
tag helper to show validation messages.When you run this example, you can test with both valid and invalid data to see how the validation works in action. Invalid data will show error messages, while valid data will save the user profile and display a success message.
In this lesson, we covered the key concepts of organizing and using validation attributes in Razor Pages:
[BindProperty]
.asp-validation-for
.Congratulations on completing this course! You've learned the essential skills needed to bind and validate data in Razor Pages. Remember to practice what you've learned by applying these skills to your own projects. Happy coding!