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:
@foreach
to display a list of products.The first step is to create a new component.
ProductList.raor
component to the Shared
folder.@page
directive at the top of the page.@page "/product-list"
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.
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.
... @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.
The next step will be Creating Navigation to create a link to the check-out page from the product list page.