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:
You can download the example code used in this topic on GitHub.
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.
Once you have the form model, you can begin to create the form.
Checkout.razor
component.@code { public CheckoutForm CheckoutForm { get; set; } = new(); }
... <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>
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...
@inject IJSRuntime JSRuntime ... @code { ... private async Task SubmitAsync() { await JSRuntime.InvokeVoidAsync("alert", $"Thank you {CheckoutForm.Name}, we will deliver to {CheckoutForm.Address}."); } }
<EditForm Model="CheckoutForm" OnValidSubmit="SubmitAsync"> ... </EditForm>
You will have the following result: