This guide builds on the previous steps of the Creating the API tutorial. This guide shows you how to bind a property of a model to the HTML tag using Blazor WebAssembly. You will be able to display the product after completing this guide.
You can download the example code used in this topic on GitHub.
The first thing when you start working with a Blazor WebAssembly is to change the BaseAddress
. BaseAddress
is the address of your API, in our case, it's http://localhost:5000
. You can change the BaseAddress
in the Program.cs
as follows:
public static async Task Main(string[] args) { ... builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new ("http://localhost:5000") }); ... }
After you have changed the BaseAddress
, you need to create a model for the product and then we will use that model later on to display the product in ProductDetail.razor
. Create a Product.cs
in the Data
folder. By default, the Data
folder is not there and therefore, you need to create it.
public class Product { public Guid Id { get; set; } public string Name { get; set; } public string Description { get; set; } }
The next step is to create a component for displaying a product.
Shared
folder and add select Add => Razor Component.@code
section of the component. Declare a list of properties that you need.@code { [Parameter] public Product Product { get; set; } [Parameter] public bool ShowBuyButton { get; set; } private bool IsAddedToCart { get; set; } }
We are going to get the product from the parent so you need to declare the Product
property with a [Parameter]
attribute. The same thing with ShowBuyButton
.
IsAddedToCart
is to check if the item is already in the cart or not.
<div class="card"> <div class="card-title"> @Product.Name </div> <div class="card-body"> @Product.Description </div> <div class="card-footer"> @if (IsAddedToCart) { <div>Added to cart</div> } else if(ShowBuyButton) { <button class="btn btn-primary" @onclick="Buy">Buy</button> } </div> </div>
IsAddedToCart
and define the Buy
method.@inject HttpClient HttpClient ... @code { ... protected override async Task OnInitializedAsync() { IsAddedToCart = await HttpClient.GetFromJsonAsync<bool>($"api/Cart/IsItemInCart?id={Product.Id}"); } private async Task Buy() { await HttpClient.PostAsync("api/Cart/AddToCart", JsonContent.Create<Guid>(Product.Id)); IsAddedToCart = true; } }
IsAddedToCart
will send a request to the API to get the result. The Buy
method will send a request to the API to add the product to the cart, after that, it will mark the product already in the cart.
The next guide will help you create a product list where you will use the ProductDetail.razor
component we just created in this guide. Continue to Passing Data to child component.