Passing data to child component
This guide builds on the first step of the Getting Started tutorial.
At this stage of development, the online shop website has a basic product detail component.
In the following sections, you will add the following feature to the website:
- Create a product list page.
- Display the details of each product on the product list page.
Create a product list page
In this section, you will update the website to display a list of products. You will use the class Product.cs
we have created before as the model for product. This section guides you through editing the Razor Component.
- Head to the
Page
folder and create a new Razor Component called ProductList.razor
.
- We will declare the product list in the
@code { }
section like this:
@using Data
<h2>ProductList</h2>
@code {
private List<Product> Products;
protected override void OnInitialized()
{
Products = new()
{
new()
{
Id = Guid.NewGuid(),
Name = "All roads lead to Blazor Server",
Description = "A tutorial book for Blazor Server technology"
},
new()
{
Id = Guid.NewGuid(),
Name = "All roads lead to Blazor WASM",
Description = "A tutorial book for Blazor WASM technology."
},
new()
{
Id = Guid.NewGuid(),
Name = "How to be a good web programmer?",
Description = "Follow the journey of a programmer."
}
};
}
}
The OnInitialized()
method fires when the page is rendered on the server. By doing this, you are telling the server to initate the value for Products
after the page is rendered. The @using
at the top of the page indicates that we are going to use every class in the Data
folder, in our case, we are using the Product.cs
from the Data
folder.
Display the product detail
Currently, the product list now has the products to display, all you need to do is display the detail of each product. Add an @foreach
syntax reference to create a foreach loop, as follows.
@foreach (var product in Products)
{
<ProductDetail Product="product"></ProductDetail>
}
The @
symbol in Razor Component to tell ASP.NET to evaluate the following C# code and render the result to the HTML template. The <ProductDetail>
tag is telling ASP.NET to look for the ProductDetail.razor
and render the component in the HTML template. All you just do is tell ASP.NET that for each the product that you have here, render one ProductDetail.razor
component and passing 2 parameters Product="product" ShowBuyButton="true"
to the child component.
What's next
You have updated your website to show the product list.
To continue exploring Blazor Server:
- Continue to Adding navigation to add a distinct URL so you can see the results of the product list.