一个简单的购物车的实现思路

刚看到一网页提问问购物车怎么实现,就把自己原来的例子整理一下://需要使用的实体类 public class CartInfo { //购物车项 public int Count { get; set; } public VWBookInfo Book { get; set; } } public class CartItem { public int CartId { get; set; } public string Title { get; set; } public Decimal Price { get; set; } public Decimal SumMoney { get; set; } public int Count { get; set; } } //将购买的书籍保存至Session中 ①根据id得到书籍信息 VWBookInfo book = this.GetBookInfoById(); ②得到Session中保存的购物车项 Dictionary<int, CartInfo> books = (Dictionary<int, CartInfo>)Session["Books"]; //判断是否为第一次购买 if (books.Count == 0) { //以前购买过 //实例化一个购物车项 CartInfo c = new CartInfo() { Book = book, Count = 1 }; //将购物车项存入Dictionary集合中 books.Add(book.ID, c); } else { //不是第一次购买 if (books.ContainsKey(book.ID)) { //判断以前购买的书籍中是否包含正准备购买的书籍 //根据ID取出以前购买过的书籍的信息 CartInfo c = books.Where(b => b.Key == book.ID).Single().Value; //将购物车项中对应的数量加一 c.Count = c.Count + 1; } else { //以前购买的书籍中不包含正在购买的书籍 //实例化一个购物车项 CartInfo c = new CartInfo() { Book = book, Count = 1 }; //将购物车项存入Dictionary集合中 books.Add(book.ID, c); } } this.Session["Books"] = books; //将Session中保存的Dictionary集合中的数据取出放入List泛型集合中 //取出Session中保存的集合 Dictionary<int, CartInfo> books = (Dictionary<int, CartInfo>)Session["Books"]; //实例化一个List集合 List<CartItem> lstItems = new List<CartItem>(); int id = 1; //自定义序号 //将Dictionary集合中数据取出放入List泛型集合中 foreach (CartInfo c in books.Values) { CartItem item = new CartItem() { CartId = id, Title = c.Book.Title, Price = c.Book.UnitPrice, Count = c.Count, SumMoney = c.Count * c.Book.UnitPrice }; lstItems.Add(item); id++; } if (lstItems.Count > 0) { //当List集合中有数据时,将集合作为数据源绑定到控件中 this.rpGoods.DataSource = lstItems; this.rpGoods.DataBind(); } else { this.lblMsg.Text = "您的购物车中暂时没有任何商品!"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值