A shopping cart holds the products a customer selects from a catalog until checkout. Each selection records a product and quantity; the cart displays the selections and their total cost. section 8.2 section 8.2.5
The Cart model provides the core behavior:
- Add a new line for a product, or increase its quantity if it is already present. section 8.2.5
- Remove a product, calculate the sum of price times quantity, or clear all lines. section 8.2.5
Listing 8.22 The contents of the Cart.cs file in the SportsStore/Models folder
namespace SportsStore.Models {
public class Cart {
public List<CartLine> Lines { get; set; } = new List<CartLine>();
public void AddItem(Product product, int quantity) {
CartLine? line = Lines
.Where(p => p.Product.ProductID == product.ProductID)
.FirstOrDefault();
if (line == null) {
Lines.Add(new CartLine {
Product = product,
Quantity = quantity
});
} else {
line.Quantity += quantity;
}
}
public void RemoveLine(Product product) =>
Lines.RemoveAll(l => l.Product.ProductID
== product.ProductID);
public decimal ComputeTotalValue() =>
Lines.Sum(e => e.Product.Price * e.Quantity);
public void Clear() => Lines.Clear();
}
public class CartLine {
public int CartLineID { get; set; }
public Product Product { get; set; } = new();
public int Quantity { get; set; }
}
}
The Cart.cs listing shows how product IDs identify existing lines and how line quantities contribute to the total. section 8.2.5
The cart must survive separate requests. Session data initially stores its JSON representation; a cart service later takes responsibility for persistence, so the Razor Page can receive a Cart through its constructor instead of loading and saving session data in each handler. section 8.2.5 section 9.1.3
The cart Razor Page displays quantity, product, price, and subtotal. An Add To Cart button leads from a catalog product to the cart; a Remove form sends a POST selected by asp-page-handler="Remove", which invokes OnPostRemove. section 8.2 section 8.2.5 section 9.2.1
Check the arithmetic
Add one product priced at 100, one priced at 50, then three more of the first product. The cart keeps two lines and returns a total of 450. Unit tests also check adding, removing, and clearing lines; a small cart bug can spoil the whole store. section 8.2.5

