Using child component
This guide builds on the previous steps of the Binding a Model to HTML tutorial. At this stage, you already have a page to display a single product. This guide will help you to add the following feature to your online shop:
- Set URL for a component.
- Use
@foreach
to display a list of products.
Set URL for a component
The first step is to create a new component.
- Add a
ProductList.raor
component to the Shared
folder.
- Add a
@page
directive at the top of the page.
@page "/product-list"
Display a list of products
The next thing you want to do is display a list of products. To display a list of products, you need to have a list of products first.
- Create a property of
List<Product>
and initialize at OnInitializedAsync
as follows:
...
@inject HttpClient HttpClient
...
@code {
private List<Product> Products { get; set; } = new();
protected override async Task OnInitializedAsync()
{
Products = await HttpClient.GetFromJsonAsync<List<Product>>("api/Product/GetAllProducts");
}
}
Whenever the component is used or navigated, the OnInitializedAsync
will be executed and then, by using HttpClient.GetFromJsonAsync
you are getting the Products
from the API server.
- Display the list of products.
...
@foreach (var product in Products)
{
<ProductDetail Product="product" ShowBuyButton="true"></ProductDetail>
}
...
You pass each product to a ProductDetail
component and also tell the ProductDetail
to show the buy button.
What's next?
The next step will be Creating Navigation to create a link to the check-out page from the product list page.