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.

  1. Add a ProductList.raor component to the Shared folder.
  2. 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.

  1. 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.

  1. 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.

BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2025 Blazor School
An unhandled error has occurred. Reload 🗙