牛腩购物网25:购物车的实现
第二部分:购物车的实现
我们用session来保存购物车,用一个哈希表来保存商品购物车
商品1:单价,数量 商品2:单价,数量 商品3:单价,数量
购物车中的每一个商品,都是一个对象,这个对象,有单价,和数量这2个属性,购物车是很多对象的集合。
我们在model层中,增加一个 ShopItem 类, 这个就是表示 购物车 商品类
还增加一个 ShopCart 类,这个就是购物车类,里面有很多对 购物车商品的方法
ShopItem.cs
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace Niunan.Shop.Model
7: {
8: public class ShopItem
9: {
10: //这里用到 asp.net 3.5的 自动属性
11:
12: public int proid { get; set; } //商品ID
13: public decimal price { get; set; } //商品的价格
14: public int quantity { set; get; } //商品的数量
15:
16:
17: }
18: }
19:
ShopCart.cs
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Collections;// 如果我们要使用 哈希表 ,就需要引用这个集合
6:
7: namespace Niunan.Shop.Model
8: {
9: /// <summary>购物车类
10: ///
11: /// </summary>
12: public class ShopCart
13: {
14: private Hashtable _sc = new Hashtable();
15:
16: /// <summary>向购物车中,添加商品
17: ///
18: /// </summary>
19: /// <param name="proid">商品的ID</param>
20: /// <param name="item">商品</param>
21: public void Add(int proid, ShopItem item)
22: {
23: //先判断这个商品是否存在
24: if (_sc[proid] == null)
25: {
26: //不存在
27: _sc.Add(proid, item);
28: }
29: else
30: {
31: //如果存在,我们先把商品取出来,然后给商品的数量+1
32:
33: ShopItem si = _sc[proid] as ShopItem; //这里的 _sc[proid] 是指根据商品ID,获取对应的值,
34: 这个值是个object 我们需要转换为 shopitem
35: si.quantity += 1;
36: _sc[proid] = si;
37: }
38: }
39:
40: /// <summary>删除购物车中的商品
41: ///
42: /// </summary>
43: /// <param name="proid">商品的ID</param>
44: public void Delete(int proid)
45: {
46: if (_sc[proid] != null)
47: {
48: _sc.Remove(proid);
49: }
50:
51: }
52:
53: /// <summary>修改购物车中商品的数量
54: ///
55: /// </summary>
56: /// <param name="proid">商品id</param>
57: /// <param name="quantity">数量</param>
58: public void Update(int proid, int quantity)
59: {
60: //先判断有无商品
61: if (_sc[proid] != null)
62: {
63: ShopItem si = _sc[proid] as ShopItem;
64: //如果数量>0 那么就直接修改数量,否则数量为0的话,就删除掉这个商品
65: if (quantity > 0)
66: {
67: si.quantity = quantity;
68: }
69: else
70: {
71: _sc.Remove(proid);
72: }
73:
74: }
75: }
76: /// <summary>获取购物车中商品的种类的数量,例如是有多少种商品
77: ///
78: /// </summary>
79: /// <returns></returns>
80: public int GetItemCount()
81: {
82: return _sc.Count; //返回的是 哈希table 键/值 对的数量
83: }
84:
85: /// <summary>返回购物车中商品的总价
86: ///
87: /// </summary>
88: /// <returns></returns>
89: public decimal GetTotalPrice()
90: {
91: decimal total = 0;
92: //这里的 _sc.Value 是一个 iCollection, i 表示 Interface, 也就是表示是一个集合的接口
93: //如果是要绑定 gridview 或者是 repeater 等数据控件 ,必须要实现 icollection接口
94: foreach (ShopItem item in _sc.Values)
95: {
96: total += item.price * item.quantity;
97: }
98: return total;
99: }
100:
101: /// <summary>获取购物车中商品的集合,用于绑定数据控件
102: ///
103: /// </summary>
104: /// <returns></returns>
105: public ICollection GetItemList()
106: {
107: //这里的 _sc.Value 是一个 iCollection, i 表示 Interface, 也就是表示是一个集合的接口
108: //如果是要绑定 gridview 或者是 repeater 等数据控件 ,必须要实现 icollection接口
109: return _sc.Values;
110: }
111:
112: }
113: }
114:
我们来建立一个测试页面,来测试购物车。
前台test.aspx 代码
1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="Niunan.Shop.Web.test" %>
2:
3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4:
5: <html xmlns="http://www.w3.org/1999/xhtml">
6: <head runat="server">
7: <title></title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12:
13: <asp:Button ID="Button1" runat="server" Text="添加商品1" CommandArgument="1" OnClick="buy"/>
14: <asp:Button ID="Button2" runat="server" Text="添加商品2" CommandArgument="2" OnClick="buy"/>
15: <asp:Button ID="Button3" runat="server" Text="添加商品3" CommandArgument="3" OnClick="buy"/>
16: <asp:Button ID="Button4" runat="server" Text="添加商品4" CommandArgument="4" OnClick="buy"/>
17: <asp:Button ID="Button5" runat="server" Text="添加商品5" CommandArgument="5" OnClick="buy"/>
18:
19: </div>
20: <div>
21: 购物车中商品的种类:
22: <asp:Literal ID="litCount" runat="server"></asp:Literal><br />
23:
24: 购物车中商品的总价
25: <asp:Literal ID="litTotalPrice" runat="server"></asp:Literal>
26:
27: <br />
28: <br />
29: <asp:GridView ID="gdCart" runat="server">
30: </asp:GridView>
31:
32: </div>
33: </form>
34: </body>
35: </html>
36:
后台代码:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7:
8: namespace Niunan.Shop.Web
9: {
10: public partial class test : System.Web.UI.Page
11: {
12: protected void Page_Load(object sender, EventArgs e)
13: {
14: if (Session["cart"]!=null)
15: {
16: Niunan.Shop.Model.ShopCart sc = Session["cart"] as Niunan.Shop.Model.ShopCart;
17: litCount.Text = sc.GetItemCount().ToString();
18: litTotalPrice.Text = sc.GetTotalPrice().ToString("c2");
19: gdCart.DataSource = sc.GetItemList();
20: gdCart.DataBind();
21: }
22: }
23:
24: protected void buy(object sender, EventArgs e)
25: {
26: string proid = (sender as Button).CommandArgument;
27:
28: decimal price = int.Parse(proid) * 10;
29:
30: if (Session["cart"] != null)
31: {
32: //如果不等于空的话,我们就先取出来,然后再加进去
33: Niunan.Shop.Model.ShopCart sc = Session["cart"] as Niunan.Shop.Model.ShopCart;
34: sc.Add(int.Parse(proid),new Model.ShopItem{
35: proid=int.Parse(proid),price=price,quantity=1
36: });
37: Session["cart"] = sc;
38:
39: }
40: else
41: {
42: Niunan.Shop.Model.ShopCart sc = new Model.ShopCart();
43: sc.Add(int.Parse(proid), new Model.ShopItem {
44: proid = int.Parse(proid),
45: price = price,
46: quantity = 1
47: });
48:
49: //然后把购物车,放到session里面
50: Session["cart"] = sc;
51: }
52:
53: Response.Redirect(Request.Url.ToString());
54:
55:
56: }
57: }
58: }
前台的样式如下,但是,这里的girdview是我们自带的,如果我们想要修改,怎么弄呢?
我们先禁用girdview的 自动显示字段, AutoGenerateColumns="false" 然后我们开始编辑列
最后,前台代码如下:
1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="Niunan.Shop.Web.test" %>
2:
3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4: <html xmlns="http://www.w3.org/1999/xhtml">
5: <head runat="server">
6: <title></title>
7: </head>
8: <body>
9: <form id="form1" runat="server">
10: <div>
11: <asp:Button ID="Button1" runat="server" Text="添加商品1" CommandArgument="1" OnClick="buy" />
12: <asp:Button ID="Button2" runat="server" Text="添加商品2" CommandArgument="2" OnClick="buy" />
13: <asp:Button ID="Button3" runat="server" Text="添加商品3" CommandArgument="3" OnClick="buy" />
14: <asp:Button ID="Button4" runat="server" Text="添加商品4" CommandArgument="4" OnClick="buy" />
15: <asp:Button ID="Button5" runat="server" Text="添加商品5" CommandArgument="5" OnClick="buy" />
16: </div>
17: <div>
18: 购物车中商品的种类:
19: <asp:Literal ID="litCount" runat="server"></asp:Literal><br />
20: 购物车中商品的总价
21: <asp:Literal ID="litTotalPrice" runat="server"></asp:Literal>
22: <br />
23: <br />
24: <asp:GridView ID="gdCart" runat="server" EnableModelValidation="True" AutoGenerateColumns="False">
25: <Columns>
26: <asp:BoundField DataField="proid" HeaderText="商品ID" />
27: <asp:BoundField DataField="price" HeaderText="价格" />
28: <asp:TemplateField HeaderText="数量">
29: <ItemTemplate>
30: <asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("quantity") %>' ToolTip='<%#Eval("proid") %>' AutoPostBack="true" OnTextChanged="Mod"></asp:TextBox>
31: </ItemTemplate>
32: </asp:TemplateField>
33: <asp:TemplateField HeaderText="小计">
34: <ItemTemplate>
35: <%# decimal.Parse(Eval("price").ToString()) * int.Parse(Eval("quantity").ToString()) %>¥
36: </ItemTemplate>
37: </asp:TemplateField>
38: <asp:TemplateField HeaderText="操作">
39: <ItemTemplate>
40: <asp:LinkButton ID="LinkButton1" runat="server" OnClick="delete" CommandArgument='<%#Eval("proid") %>'>删除</asp:LinkButton>
41: </ItemTemplate>
42: </asp:TemplateField>
43: </Columns>
44: </asp:GridView>
45: <br />
46: <br />
47: </div>
48: </form>
49: </body>
50: </html>
51:
后台代码:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7:
8:
9: namespace Niunan.Shop.Web
10: {
11: public partial class test : System.Web.UI.Page
12: {
13: protected void Page_Load(object sender, EventArgs e)
14: {
15: if (!Page.IsPostBack) //回发的时候,我们会在page_load 看到页面上所有的控件的值,在回发的时候都被保存了下来,并且可以访问
16: {
17: if (Session["cart"] != null)
18: {
19: Niunan.Shop.Model.ShopCart sc = Session["cart"] as Niunan.Shop.Model.ShopCart;
20: litCount.Text = sc.GetItemCount().ToString();
21: litTotalPrice.Text = sc.GetTotalPrice().ToString("c2");
22: gdCart.DataSource = sc.GetItemList();
23: gdCart.DataBind();
24: }
25: }
26: }
27:
28: //购买
29: protected void buy(object sender, EventArgs e)
30: {
31: string proid = (sender as Button).CommandArgument;
32:
33: decimal price = int.Parse(proid) * 10;
34:
35: if (Session["cart"] != null)
36: {
37: //如果不等于空的话,我们就先取出来,然后再加进去
38: Niunan.Shop.Model.ShopCart sc = Session["cart"] as Niunan.Shop.Model.ShopCart;
39: sc.Add(int.Parse(proid), new Model.ShopItem
40: {
41: proid = int.Parse(proid),
42: price = price,
43: quantity = 1
44: });
45: Session["cart"] = sc;
46:
47: }
48: else
49: {
50: Niunan.Shop.Model.ShopCart sc = new Model.ShopCart();
51: sc.Add(int.Parse(proid), new Model.ShopItem
52: {
53: proid = int.Parse(proid),
54: price = price,
55: quantity = 1
56: });
57:
58: //然后把购物车,放到session里面
59: Session["cart"] = sc;
60: }
61:
62: Response.Redirect(Request.Url.ToString());
63:
64:
65: }
66:
67: //修改购物车中商品的数量
68: protected void Mod(object sender, EventArgs e)
69: {
70: TextBox txt = (sender as TextBox); //这里是 TextBox 获取的方法 ,先转换为一个 TextBox 对象
71: string proid = txt.ToolTip;
72: string quantity = txt.Text;
73: int x;
74: //如果数量不能转换,我们就强制数量为1
75: if (!int.TryParse(quantity, out x))
76: {
77: x = 1;
78: }
79: if (Session["cart"] != null)
80: {
81: //如果不等于空的话,我们就先取出来,然后再加进去
82: Niunan.Shop.Model.ShopCart sc = Session["cart"] as Niunan.Shop.Model.ShopCart;
83: sc.Update(int.Parse(proid), x);
84: Session["cart"] = sc;
85:
86: }
87: Response.Redirect(Request.Url.ToString());
88:
89: }
90:
91: //删除购物车中的商品
92: protected void delete(object sender, EventArgs e)
93: {
94: string proid = (sender as LinkButton).CommandArgument;
95: if (Session["cart"] != null)
96: {
97: Niunan.Shop.Model.ShopCart sc = Session["cart"] as Niunan.Shop.Model.ShopCart;
98: sc.Delete(int.Parse(proid));
99: Session["cart"] = sc;
100: Response.Redirect(Request.Url.ToString());
101: }
102:
103: }
104:
105:
106:
107:
108: }
109: }