C#购物车 方法

C购物车  方法 - 网站笔记 - 网站笔记的博客
这里是一个简单的 C# 购物车的前端和后端代码示例: 后端代码(使用 ASP.NET MVC): ```csharp using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace ShoppingCart.Controllers { public class HomeController : Controller { // 商品列表 private static readonly List<Product> Products = new List<Product> { new Product {Id = 1, Name = "商品1", Price = 10}, new Product {Id = 2, Name = "商品2", Price = 20}, new Product {Id = 3, Name = "商品3", Price = 30}, new Product {Id = 4, Name = "商品4", Price = 40}, new Product {Id = 5, Name = "商品5", Price = 50}, }; // 购物车 private static readonly List<CartItem> CartItems = new List<CartItem>(); public ActionResult Index() { // 把商品列表传递给前端页面 ViewBag.Products = Products; return View(); } // 添加商品到购物车 public ActionResult AddToCart(int id) { var product = Products.FirstOrDefault(p => p.Id == id); if (product != null) { // 查找购物车里是否已经有该商品,有则数量加 1,否则添加一条新的购物车项 var cartItem = CartItems.FirstOrDefault(ci => ci.Product.Id == product.Id); if (cartItem != null) { cartItem.Quantity++; } else { CartItems.Add(new CartItem {Product = product, Quantity = 1}); } } return RedirectToAction("Index"); } // 清空购物车 public ActionResult ClearCart() { CartItems.Clear(); return RedirectToAction("Index"); } } // 商品类 public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } // 购物车项类 public class CartItem { public Product Product { get; set; } public int Quantity { get; set; } } } ``` 前端代码: ```html @{ ViewBag.Title = "购物车"; } <h2>商品列表</h2> <ul> @foreach (var product in ViewBag.Products) { <li>@product.Name - ¥@product.Price <a href="@Url.Action("AddToCart", new {id = product.Id})">加入购物车</a></li> } </ul> <h2>购物车</h2> @if (HomeController.CartItems.Count == 0) { <p>购物车是空的</p> } else { <ul> @foreach (var cartItem in HomeController.CartItems) { <li>@cartItem.Product.Name - ¥@cartItem.Product.Price - 数量:@cartItem.Quantity</li> } </ul> <p><a href="@Url.Action("ClearCart")">清空购物车</a></p> } ``` 这里的代码实现了一个简单的购物车功能,包括商品列表、添加商品到购物车、清空购物车等功能。当用户点击“加入购物车”按钮时,会将商品添加到后端的购物车列表中;当用户查看购物车时,会从后端获取购物车列表并显示在前端页面上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值