In the previous tutorial of this tutorial series, you have learned about Dependency Injection. In this tutorial, you will learn how to create a form to collect user information.
You can download the example code used in this topic on GitHub.
Before you create the form, you need to create a form model first. The form model will define which field you want to show in the form and the validation rules of each field. Create a new class CheckoutForm.cs
in the Models
folder which we have created before.
public class CheckoutForm { [Required(ErrorMessage = "Name is required.")] public string Name { get; set; } = ""; [Required(ErrorMessage = "We need the address to deliver the product.")] public string Address { get; set; } = ""; }
We are going to use the built-in System.ComponentModel.DataAnnotations
library to do the validation.
Once you have the form model, the next step is to create the form itself.
Checkout.razor
which we have created in the previous tutorial.@code { public CheckoutForm CheckoutForm { get; set; } = new(); ... }
EditForm
component to show the form in the UI section. EditForm
is a pre-build component of Blazor.<EditForm class="vstack gap-3" Model="CheckoutForm"> <DataAnnotationsValidator></DataAnnotationsValidator> <div> <label class="form-label" for="name">Name:</label> <InputText id="name" class="form-control" @bind-Value="CheckoutForm.Name"></InputText> <ValidationMessage class="form-control" For="()=>CheckoutForm.Name"></ValidationMessage> </div> <div> <label class="form-label" for="address">Address:</label> <InputText id="address" class="form-control" @bind-Value="CheckoutForm.Address"></InputText> <ValidationMessage class="form-control" For="()=>CheckoutForm.Address"></ValidationMessage> </div> <div> <button class="btn btn-primary" type="submit">Submit</button> </div> </EditForm>
You don't need to test the form in a real life project, but for the demonstrate purpose, you are going to test the form by JavaScript. Whenever a use press Submit button, the form will validate the values and show errors if any.
IJSRuntime
to invoke JavaScript from C#. This step is optional. Add the following code to the directive section.@inject IJSRuntime JSRuntime
private async Task SubmitAsync() { await JSRuntime.InvokeVoidAsync("alert", $"Thank you {CheckoutForm.Name}, we will deliver to {CheckoutForm.Address}."); }
<EditForm class="vstack gap-3" Model="CheckoutForm" OnValidSubmit="SubmitAsync"> ... </EditForm>