Collect information
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.
Create the form model.
Create the form.
Test the form.
You can download the example code used in this topic on GitHub.
Create the form model
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.
Create the form
Once you have the form model, the next step is to create the form itself.
Open your Checkout.razor
which we have created in the previous tutorial.
Declare your form model in the code section.
@code {
public CheckoutForm CheckoutForm { get; set; } = new();
...
}
Use 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>
Test the form
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.
Inject IJSRuntime
to invoke JavaScript from C#. This step is optional. Add the following code to the directive section.
@inject IJSRuntime JSRuntime
Add a submit method to the code section.
private async Task SubmitAsync()
{
await JSRuntime.InvokeVoidAsync("alert", $"Thank you {CheckoutForm.Name}, we will deliver to {CheckoutForm.Address}.");
}
Use the submit method we just created in the form.
<EditForm class="vstack gap-3" Model="CheckoutForm" OnValidSubmit="SubmitAsync">
...
</EditForm>