Collect information
This tutorial is a continuation of the previous tutorial. You are going to learn how to collect the user's information using the EditForm
component. In this tutorial:
Create the form model.
Create the form.
Handle form submission.
You can download the example code used in this topic on GitHub.
Create the form model
We are going to collect the user's name and the address by 2 textboxes in the form. You need to create a form model with 2 properties for the name and the address. For example:
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; } = "";
}
When creating the form model, you can set the validation rules for each property. In the example, we are going to make both Name
and Address
and required. Otherwise, an error message will show up. Those validations are executed in the frontend side , you will learn more about form validation at the later tutorials.
Create the form
Once you have the form model, you can begin to create the form.
Open your Checkout.razor
component.
Declare the form model at the code section as follows:
@code {
public CheckoutForm CheckoutForm { get; set; } = new();
}
Define the UI for the form.
...
<EditForm Model="CheckoutForm">
<DataAnnotationsValidator></DataAnnotationsValidator>
<div>
<label>Name:</label>
<InputText @bind-Value="CheckoutForm.Name"></InputText>
<ValidationMessage class="form-control" For="()=>CheckoutForm.Name"></ValidationMessage>
</div>
<div>
<label for="address">Address:</label>
<InputText @bind-Value="CheckoutForm.Address"></InputText>
<ValidationMessage For="()=>CheckoutForm.Address"></ValidationMessage>
</div>
<div>
<button type="submit">Submit</button>
</div>
</EditForm>
Handle form submission
Once the user has entered the valid information to the UI, you need to handle that information afterward. Handling information process such as maybe check for additional rules, modify form data, submit the data to the server, etc...
Declare a method to handle the data.
@inject IJSRuntime JSRuntime
...
@code {
...
private async Task SubmitAsync()
{
await JSRuntime.InvokeVoidAsync("alert", $"Thank you {CheckoutForm.Name}, we will deliver to {CheckoutForm.Address}.");
}
}
Pass the handle method to the form.
<EditForm Model="CheckoutForm" OnValidSubmit="SubmitAsync">
...
</EditForm>
You will have the following result: