Blazor是微软推出的基于.NET的前端框架,允许开发者使用C#语言编写前端交互逻辑,实现购物车这类常见业务功能不需要依赖JavaScript,整体开发流程更符合.NET开发者的习惯。下面我们就基于Blazor Server模式,一步步实现一个具备基础功能的简单购物车。

准备工作
首先我们需要创建一个Blazor Server应用项目,在Visual Studio中选择对应模板创建即可。之后我们需要定义两个基础模型类,分别是商品模型和购物车项模型,这两个类会贯穿整个购物车功能的实现过程。
// 商品模型
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string ImageUrl { get; set; }
}
// 购物车项模型
public class CartItem
{
public Product Product { get; set; }
public int Quantity { get; set; }
// 计算单项总价
public decimal TotalPrice => Product.Price * Quantity;
}
实现购物车状态管理
购物车的数据需要在多个组件之间共享,比如商品列表组件添加商品后,购物车侧边栏需要同步更新,因此我们需要创建一个购物车状态服务,用来存储和管理购物车的所有数据。
// 购物车状态服务,注册为Scoped生命周期
public class CartService
{
// 存储购物车项列表
public List<CartItem> CartItems { get; private set; } = new List<CartItem>();
// 添加商品到购物车
public void AddToCart(Product product)
{
var existingItem = CartItems.FirstOrDefault(item => item.Product.Id == product.Id);
if (existingItem != null)
{
// 商品已存在,数量加1
existingItem.Quantity++;
}
else
{
// 商品不存在,新增购物车项
CartItems.Add(new CartItem { Product = product, Quantity = 1 });
}
// 触发状态变更事件
NotifyStateChanged();
}
// 调整购物车项数量
public void UpdateQuantity(int productId, int quantity)
{
var item = CartItems.FirstOrDefault(i => i.Product.Id == productId);
if (item != null)
{
if (quantity <= 0)
{
// 数量小于等于0时移除该项
CartItems.Remove(item);
}
else
{
item.Quantity = quantity;
}
NotifyStateChanged();
}
}
// 从购物车移除商品
public void RemoveFromCart(int productId)
{
var item = CartItems.FirstOrDefault(i => i.Product.Id == productId);
if (item != null)
{
CartItems.Remove(item);
NotifyStateChanged();
}
}
// 计算购物车总价
public decimal GetTotalPrice()
{
return CartItems.Sum(item => item.TotalPrice);
}
// 状态变更事件,用于通知组件更新
public event Action StateChanged;
private void NotifyStateChanged() => StateChanged?.Invoke();
}
创建完服务后,需要在Program.cs中注册该服务,确保组件可以正常注入使用:
builder.Services.AddScoped<CartService>();
商品列表组件实现
我们先实现商品展示列表组件,这个组件会展示预设的商品数据,并且每个商品都有添加到购物车的按钮。
<h3>商品列表</h3>
<div class="product-list">
@foreach (var product in Products)
{
<div class="product-card">
<h4>@product.Name</h4>
<p>价格:@product.Price.ToString("C")</p>
<button @onclick="() => AddProductToCart(product)">加入购物车</button>
</div>
}
</div>
@code {
[Inject]
private CartService CartService { get; set; }
// 模拟商品数据
private List<Product> Products = new List<Product>
{
new Product { Id = 1, Name = "无线鼠标", Price = 89.9m, ImageUrl = "" },
new Product { Id = 2, Name = "机械键盘", Price = 299m, ImageUrl = "" },
new Product { Id = 3, Name = "USB扩展坞", Price = 129m, ImageUrl = "" },
new Product { Id = 4, Name = "笔记本支架", Price = 69m, ImageUrl = "" }
};
private void AddProductToCart(Product product)
{
CartService.AddToCart(product);
}
}
购物车组件实现
接下来实现购物车组件,这个组件会展示当前购物车中的所有商品,支持调整数量、删除商品,同时显示总价。
<h3>我的购物车</h3>
@if (CartService.CartItems.Count == 0)
{
<p>购物车为空,快去添加商品吧</p>
}
else
{
<table>
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<tbody>
@foreach (var item in CartService.CartItems)
{
<tr>
<td>@item.Product.Name</td>
<td>@item.Product.Price.ToString("C")</td>
<td>
<button @onclick="() => UpdateItemQuantity(item.Product.Id, item.Quantity - 1)">-</button>
@item.Quantity
<button @onclick="() => UpdateItemQuantity(item.Product.Id, item.Quantity + 1)">+</button>
</td>
<td>@item.TotalPrice.ToString("C")</td>
<td>
<button @onclick="() => RemoveItem(item.Product.Id)">删除</button>
</td>
</tr>
}
</tbody>
</table>
<p class="total-price">总价:@CartService.GetTotalPrice().ToString("C")</p>
}
@code {
[Inject]
private CartService CartService { get; set; }
protected override void OnInitialized()
{
// 订阅状态变更事件,服务数据更新时重新渲染组件
CartService.StateChanged += StateHasChanged;
}
private void UpdateItemQuantity(int productId, int quantity)
{
CartService.UpdateQuantity(productId, quantity);
}
private void RemoveItem(int productId)
{
CartService.RemoveFromCart(productId);
}
public void Dispose()
{
// 组件销毁时取消订阅,避免内存泄漏
CartService.StateChanged -= StateHasChanged;
}
}
主页面整合组件
最后我们在主页面中整合商品列表组件和购物车组件,让整个功能可以正常运行。
@page "/"
<div class="main-container">
<div class="product-section">
<ProductList />
</div>
<div class="cart-section">
<Cart />
</div>
</div>
到这里我们就完成了一个简单的Blazor购物车功能,这个实现包含了商品展示、添加商品、数量调整、删除商品、总价计算等核心能力,同时也用到了Blazor的服务注入、组件通信、状态管理等基础特性,开发者可以在此基础上根据需求扩展更多功能,比如商品库存校验、结算流程、本地存储购物车数据等。
Blazor购物车ASP.NET_Core组件通信状态管理修改时间:2026-06-26 18:51:42