Manage shopping cart
In the previous tutorial of this tutorial series, you have learned about component in basic. In this tutorial, you will learn another building block of Blazor: Dependency Injection. Dependency Injection is a technique that lets you manage the website's state.
- Create a cart service with Dependency Injection.
- Allow user to put product to the cart.
- Allow user to review their cart.
You can download the example code used in this topic on GitHub.
Create a cart service
This cart service will hold the information about the product which is selected by the user. This is also known as storing the website's state. There are many places to store that state. For the sake of simplicity, we are going to store the website's state in the memory.
- Create a new class
CartService.cs
in your Services
folder. The Services
folder was created in the previous tutorial in this tutorial section.
- Add a public property to store the products which are selected by the user.
public List<Product> SelectedItems { get; set; } = new();
- Add a method to add a product to the cart. This method will be invoked when the user presses the Buy button.
public void AddProductToCart(Guid productId)
{
var product = ProductProviderService.Products.First(p => p.Id == productId);
if (SelectedItems.Contains(product) is false)
{
SelectedItems.Add(product);
}
}
- Register the
CartService
in the Program.cs
.
builder.Services.AddScoped<CartService>();
Allow user to put product to the cart
Next step, we are going to use the CartService
we just created to store the cart information.
- Open
ProductList.razor
we created at the previous tutorial.
- Inject the
CartService
. Add the following code to the directive section (at the start of the component).
@inject CartService CartService
- Add the method to the code section for the Buy button.
@code {
...
private void Buy(Guid productId)
{
CartService.AddProductToCart(productId);
}
}
- Invoke the method when the button Buy is clicked. Add the directive
@onclick
to the Buy button.
<button class="btn btn-primary" type="button" @onclick="() => Buy(product.Id)">Buy</button>
Allow user to review their cart
After the user is able to put product to the cart, we will let them review their cart.
- Create a new Razor Component
Checkout.razor
in the Pages
folder.
- Inject the
CartService
. Add the following code to the directive section (at the start of the component).
@inject CartService CartService
- Use the
ProductList
component which we have created at the previous tutorial to display the products in the cart. Add the following code to the UI section (below the directive section).
<h3>You have @CartService.SelectedItems.Count in cart:</h3>
<ProductList Products="CartService.SelectedItems"></ProductList>
You can see the result as follow: