Managing data

This guide builds on the third step of the Getting Started tutorial, Passing Data to child component, and Adding Navigation. At this stage of development, the online shop has a product list and the user can navigate to the product list and from the product list the user can also go to the check-out page.

This step of the tutorial guides you through creating a shopping cart in the following phases:

  • Implement the purchase feature
  • Implement the cart system.
  • Show the cart item on the check-out page

Create the product service

In Blazor Server, a service is an instance of a class that you can make available anywhere on your website using Blazor Server's dependency injection system.

Currently, the product list is only on the product list page and if the check-out page needs to display some of the product then it is not possible.

The next step is to build a way for the website to share the product list so that both product list page and check-out page can access the product list. This section will walk you through adding a product service to share the list of products.

Define a product service

  1. Add a new class to the Data folder named ProductService.cs, as follows:
public class ProductService
{
    private readonly List<Product> _products;

    public ProductService()
    {
        _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."
            }
        };
    }

    public List<Product> GetAllProducts()
    {
        return _products;
    }
}
  1. Register ProductService in Startup.cs. To do that, go to the Startup.cs and look for the ConfigureServices method, register ProductService, as follows:
public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton<ProductService>();
}

ProductService will serve as a data provider and the data will be stored in a database. Right now, you need to declare ProductService as a singleton because singleton services will serve the same data on the entire website so that you can simulate the data from the database.

Use the product service

This section will walk you through using the ProductService to provide data for the product list page.

  1. Navigate to the ProductList.razor and inject the ProductService into by adding the following code to the top of the page.
@inject ProductService ProductService

The @inject directive takes 2 arguments: the first is the class name and the second is the instance name of the injecting instance. In this case, you are injecting the ProductService and calling it as ProductService. It is a good practice to have the same instance name and class name of the injecting instance. The next step is to get the data from ProductService.

  1. Use the ProductService to provide data for the product list page. Update the @code{} section of the ProductList.razor as follows:
@code {
    private List<Product> Products;

    protected override void OnInitialized()
    {
        Products = ProductService.GetAllProducts();
    }
}

Create the cart service

The next step is to build a way for users to add products to a cart. This section walks you through implementing a Buy button and setting up a cart service to store information about products in the cart.

Define a cart service

  1. Add a new class to the Data folder named CartService.cs, as follows:
public class CartService
{
    private readonly List<Product> _items;

    public CartService()
    {
        _items = new();
    }

    public void AddToCart(Product item)
    {
        _items.Add(item);
    }

    public List<Product> GetProductsInCart()
    {
        return _items;
    }
}
  1. Register the CartService in Startup.cs as follows:
services.AddScoped<CartService>();

CartService will serve data differently for each customer so you will register the CartService as a scoped service. We will have a deeper look at all types of services later.

Use the cart service

This section will walk you through using the CartService to add a product to the cart.

  1. In ProductDetail.razor, inject the CartService.
@inject CartService CartService
  1. Implement the Buy method in @code{} section, which adds the current product to the cart.
private void Buy()
{
    CartService.AddToCart(Product);
}

Create the checkout view

For customers to checkout, they need to see their cart, you can create the checkout view in two steps:

  1. Create a checkout component and configure routing to the new component.
  2. Display the items in the cart.

Set up the checkout component

To create the checkout view, follow the same steps you did to create the ProductDetail.razor and configure routing for the new component.

  1. Generate a checkout component named Checkout.razor by right-clicking the Pages folder, choosing Add, and Razor Component.
  2. Add @page directive at the top of the component and add a route for the component Checkout.razor with the path "/checkout".
@page "/check-out"
  1. Verify the new Checkout.razor works as expected by clicking the Check-out link in the product list page. You can see the "Checkout" default text, and the URL has the pattern https://localhost:port/check-out where port is different for your project.

Display the items in the cart

This section shows you how to use the cart service to display the products in the cart.

  1. In the Checkout.razor, import Data and inject the CartService.
@using Data;

@page "/check-out"
@inject CartService CartService
  1. Define a list of products in the cart and initialize it in the @code{} section.
private List<Product> ProductsInCart = new();

protected override void OnInitialized()
{
    ProductsInCart = CartService.GetProductsInCart();
}
  1. Update HTML template to display the items.
<div>Products in cart:</div>
<div class="d-flex flex-column">
    @foreach (var product in ProductsInCart)
    {
        <ProductDetail Product="product" ShowBuyButton="false"></ProductDetail>
    }
</div>

What's next

You now have an online shop with a product catalog, a shopping cart, and you can look up the items in the cart.

To continue exploring Blazor Server:

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 🗙