刚看到一网页提问问购物车怎么实现,就把自己原来的例子整理一下:
//需要使用的实体类
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 = "您的购物车中暂时没有任何商品!";
}