This guide builds on the previous steps in Creating Navigation guide. At this stage, your website should have a product list page that displays all the products, each product has its own Buy button. There is also a link to the checkout page.
This guide will walk you through on how to create a form for users to input their information.
To have a form in Blazor WebAssembly, you will need a model for it. Add a CheckoutInfo.cs
class to the Data
folder.
public class CheckoutInfo { [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; } }
In the Checkout.razor
, initialize CheckoutInfo
at the @code
section:
... @code { private CheckoutInfo CheckoutInfo = new(); }
Once you have the form model and initialized it, you can use EditForm
pre-built component to create the form.
<EditForm Model="CheckoutInfo" OnValidSubmit="SubmitAsync"> <DataAnnotationsValidator></DataAnnotationsValidator> <div> <label class="col-form-label" for="name">Name:</label> <InputText id="name" class="form-control" @bind-Value="CheckoutInfo.Name"></InputText> <ValidationMessage class="form-control" For="()=>CheckoutInfo.Name"></ValidationMessage> </div> <div> <label class="col-form-label" for="address">Address:</label> <InputText id="address" class="form-control" @bind-Value="CheckoutInfo.Address"></InputText> <ValidationMessage class="form-control" For="()=>CheckoutInfo.Address"></ValidationMessage> </div> <div> <button class="btn btn-primary" type="submit">Submit</button> </div> </EditForm>
This form has some validation and also, shows validation message if any validation fails.
The final step would be submitting the data to the API after validating is done.
IJSRuntime
and HttpClient
at the top of the component:@using System.Net @inject HttpClient HttpClient @inject IJSRuntime JsRuntime
The HttpClient
will help you to send requests to the API and the IJSRuntime
will help you to call the alert
function of JavaScript to notify messages.
SubmitAsync
:@code { ... private async Task SubmitAsync() { var response = await HttpClient.PostAsJsonAsync<CheckoutInfo>("api/Checkout/Checkout", CheckoutInfo); string message = await response.Content.ReadAsStringAsync(); if (response.StatusCode is HttpStatusCode.OK) { await JsRuntime.InvokeVoidAsync("alert", message); } } }
Your first Blazor WebAssembly now looks like this: