Utilizing Blazor EditForm with Model Binding and Data Annotations
Introduction to Blazor EditForm
In my recent projects, I chose Blazor EditForm for its simplicity, powerful features, and seamless integration with Blazor applications. Using Blazor EditForm was a breeze in comparison to my past experiences with handling forms and user input in ASP.NET Core projects.
Essential imports
Before we start working with Blazor EditForm, it's important to have the necessary namespaces included in the project.
Fortunately, the Blazor project template makes this process easy by including the required namespace by default in the app's _Imports.razor
file.
By adding @using Microsoft.AspNetCore.Components.Forms
to the _Imports.razor
file, you make the namespace available in all of the Razor component files (.razor) throughout your app without the need for explicit @using
directives.
Additionally, to ensure smooth functionality in your .razor files, don't forget to include using Microsoft.AspNetCore.Components;
as well.
Example: Student Models
Below the StudentModel class that will be used with an EditForm component.
public class StudentModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Course { get; set; }
public int Code { get; set; }
public int AvailableHours { get; set; }
}
Blazor EditForm with Student Model
This code shows an example of the Blazor EditForm that uses the Student model to bind input fields to properties in the model.
When the form is submitted, the AddStudent
method is called to process the form data.
@page "/student-form"
<EditForm Model="@studentModel" OnSubmit="@AddStudent">
<InputText id="name" @bind-Value="studentModel.FirstName" />
<button type="submit">Submit</button>
</EditForm>
@code {
private StudentModel studentModel = new();
private void AddStudent()
{
await StudentService.AddStudentASync(studentModel);
}
}
Data annotations validation
In Blazor EditForm, using data annotations validation helps simplify the validation process and ensures the form inputs meet specific requirements.
With the System.ComponentModel.DataAnnotations
namespace, it is possible to define various validation rules by decorating your model properties with attributes.
The StudentModel example with data annotations:
public class StudentModel
{
[Required(ErrorMessage = "First name is required.")]
[StringLength(15, ErrorMessage = "First name must not exceed 15 characters.")]
public string FirstName { get; set; }
}
In this example, the FirstName property is marked as required using the RequiredAttribute and set a maximum string length limit of 15 characters with the StringLengthAttribute. Also added a custom error messages to inform users of any validation issues.
When the user submits the form, the FirstName property will be validated against these requirements. If the input is empty or exceeds 15 characters, the corresponding error message will be displayed, providing clear feedback to the user.
Implementing data annotations validation
To implement data annotations validation in Blazor EditForm we have to modify our earlier StudentForm component to include data annotations validation. Steps to do so:
- Replace OnSubmit with OnValidSubmit
- Add ValidationSummary component to display validation messages when the form is invalid on submission.
- Attach validation support using data annotations by adding a DataAnnotationsValidator component.
The modified StudentForm component:
@page "/student-form"
<EditForm Model="@studentModel" OnValidSubmit="@AddStudent">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText id="firstName" @bind-Value="studentModel.FirstName" />
<button type="submit">Submit</button>
</EditForm>
@code {
private StudentModel studentModel = new();
private void AddStudent()
{
await StudentService.AddStudentASync(studentModel);
}
}
With these changes, if the user leaves the First Name field blank, they will see the error message "First name is required." in the ValidationSummary component. If the user enters a value greater than 15 characters in the First Name field, they will see the error message "First name must not exceed 15 characters."