其他分享
首页 > 其他分享> > [网络收集]利用Session对象实现购物车

[网络收集]利用Session对象实现购物车

作者:互联网

来自森大科技官方博客
http://www.cnsendblog.com/index.php/?p=338
GPS平台、网站建设、软件开发、系统运维,找森大网络科技!
http://cnsendnet.taobao.com

 

//shopcart.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text.RegularExpressions; 

 


public partial class shopCart : System.Web.UI.Page
{
    CommonClass ccObj = new CommonClass();
    DBClass dbObj = new DBClass();
    string strSql;
    DataTable dtTable;
    Hashtable hashCar;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["ShopCart"] == null)
            {
                //如果没有购物,则给出相应信息,并隐藏按钮
                this.labMessage.Text = "您还没有购物!";
                this.labMessage.Visible = true;        //显示提示信息
                this.lnkbtnCheck.Visible = false;      //隐藏“前往服务台”按钮
                this.lnkbtnClear.Visible = false;      //隐藏“清空购物车”按钮
                this.lnkbtnContinue.Visible = false;   //隐藏“继续购物”按钮

            }
            else
            {
                hashCar = (Hashtable)Session["ShopCart"]; //获取其购物车
                if (hashCar.Count == 0)
                {
                    //如果没有购物,则给出相应信息,并隐藏按钮
                    this.labMessage.Text = "您购物车中没有商品!";
                    this.labMessage.Visible = true;        //显示提示信息
                    this.lnkbtnCheck.Visible = false;      //隐藏“前往服务台”按钮
                    this.lnkbtnClear.Visible = false;      //隐藏“清空购物车”按钮
                    this.lnkbtnContinue.Visible = false;   //隐藏“继续购物”按钮

                }
                else
                {
                    //设置购物车内容的数据源
                    dtTable = new DataTable();
                    DataColumn column1 = new DataColumn("No");        //序号列
                    DataColumn column2 = new DataColumn("BookID");    //书籍ID代号
                    DataColumn column3 = new DataColumn("BookName");  //书籍名称
                    DataColumn column4 = new DataColumn("Num");       //数量
                    DataColumn column5 = new DataColumn("price");     //单价
                    DataColumn column6 = new DataColumn("totalPrice");//总价
                    dtTable.Columns.Add(column1);  //添加新列            
                    dtTable.Columns.Add(column2);
                    dtTable.Columns.Add(column3);
                    dtTable.Columns.Add(column4);
                    dtTable.Columns.Add(column5);
                    dtTable.Columns.Add(column6);
                    DataRow row;
                    //对数据表中每一行进行遍历,给每一行的新列赋值
                    //foreach (object key in hashCar.Keys)
                    //{
                    //    row = dtTable.NewRow();
                    //    row["BookID"] = key.ToString();
                    //    row["Num"] = hashCar[key].ToString();
                    //    dtTable.Rows.Add(row);
                    //}
                    foreach (DictionaryEntry hash in hashCar)
                    {
                        row = dtTable.NewRow();
                        row["BookID"] = hash.Key.ToString();
                        row["Num"] = hash.Value.ToString();
                        dtTable.Rows.Add(row);
                    }
                    //计算价格
                    DataTable dstable;
                    int i = 1;
                    float price;//商品单价
                    int count;  //商品数量
                    float totalPrice = 0; //商品总价格
                    foreach (DataRow drRow in dtTable.Rows)
                    {
                        strSql = "select BookName,HotPrice from tb_BookInfo where BookID=" + Convert.ToInt32(drRow["BookID"].ToString());
                        dstable = dbObj.GetDataSetStr(strSql, "tbGI");
                        drRow["No"] = i;//序号
                        drRow["BookName"] = dstable.Rows[0][0].ToString();//书籍名称
                        drRow["price"] = (dstable.Rows[0][1].ToString());//单价
                        price = float.Parse(dstable.Rows[0][1].ToString());//单价
                        count = Int32.Parse(drRow["Num"].ToString());
                        drRow["totalPrice"] = price * count; //总价
                        totalPrice += price * count; //计算合价
                        i++;
                    }
                    this.labTotalPrice.Text = "总价:" + totalPrice.ToString();  //显示所有商品的价格
                    this.gvShopCart.DataSource = dtTable.DefaultView;   //绑定GridView控件
                    this.gvShopCart.DataKeyNames = new string[] { "BookID" };
                    this.gvShopCart.DataBind();
                }
            }
        
        }
       
    }
    public void bind()
    {
        if (Session["ShopCart"] == null)
        {
            //如果没有购物,则给出相应信息,并隐藏按钮
            this.labMessage.Text = "您还没有购物!";
            this.labMessage.Visible = true;        //显示提示信息
            this.lnkbtnCheck.Visible = false;      //隐藏“前往服务台”按钮
            this.lnkbtnClear.Visible = false;      //隐藏“清空购物车”按钮
            this.lnkbtnContinue.Visible = false;   //隐藏“继续购物”按钮
            
        }
        else
        {
            hashCar = (Hashtable)Session["ShopCart"]; //获取其购物车
            if (hashCar.Count == 0)
            {
                //如果没有购物,则给出相应信息,并隐藏按钮
                this.labMessage.Text = "您购物车中没有商品!";
                this.labMessage.Visible = true;        //显示提示信息
                this.lnkbtnCheck.Visible = false;      //隐藏“前往服务台”按钮
                this.lnkbtnClear.Visible = false;      //隐藏“清空购物车”按钮
                this.lnkbtnContinue.Visible = false;   //隐藏“继续购物”按钮
               
            }
            else
            {
                //设置购物车内容的数据源
                dtTable = new DataTable();
                DataColumn column1 = new DataColumn("No");        //序号列
                DataColumn column2 = new DataColumn("BookID");    //书籍ID代号
                DataColumn column3 = new DataColumn("BookName");  //书籍名称
                DataColumn column4 = new DataColumn("Num");       //数量
                DataColumn column5 = new DataColumn("price");     //单价
                DataColumn column6 = new DataColumn("totalPrice");//总价
                dtTable.Columns.Add(column1);  //添加新列            
                dtTable.Columns.Add(column2);
                dtTable.Columns.Add(column3);
                dtTable.Columns.Add(column4);
                dtTable.Columns.Add(column5);
                dtTable.Columns.Add(column6);
                DataRow row;
                //对数据表中每一行进行遍历,给每一行的新列赋值
                foreach (object key in hashCar.Keys)
                {
                    row = dtTable.NewRow();
                    row["BookID"] = key.ToString();
                    row["Num"] = hashCar[key].ToString();
                    dtTable.Rows.Add(row);
                }
                //计算价格
                DataTable dstable;
                int i = 1;
                float price;//商品单价
                int count;  //商品数量
                float totalPrice = 0; //商品总价格
                foreach (DataRow drRow in dtTable.Rows)
                {
                    strSql = "select BookName,HotPrice from tb_BookInfo where BookID=" + Convert.ToInt32(drRow["BookID"].ToString());
                    dstable = dbObj.GetDataSetStr(strSql, "tbGI");
                    drRow["No"] = i;//序号
                    drRow["BookName"] = dstable.Rows[0][0].ToString();//书籍名称
                    drRow["price"] = (dstable.Rows[0][1].ToString());//单价
                    price = float.Parse(dstable.Rows[0][1].ToString());//单价
                    count = Int32.Parse(drRow["Num"].ToString());
                    drRow["totalPrice"] = price * count; //总价
                    totalPrice += price * count; //计算合价
                    i++;
                }
                this.labTotalPrice.Text = "总价:" + totalPrice.ToString();  //显示所有商品的价格
                this.gvShopCart.DataSource = dtTable.DefaultView;   //绑定GridView控件
                this.gvShopCart.DataKeyNames=new string[] {"BookID"};
                this.gvShopCart.DataBind();
            }
        }
            
    
    
    }
    protected void lnkbtnUpdate_Click(object sender, EventArgs e)
    {
        hashCar = (Hashtable)Session["ShopCart"];  //获取其购物车
        //使用foreach语句,遍历更新购物车中的商品数量
        foreach (GridViewRow gvr in this.gvShopCart.Rows)
        {
            TextBox otb = (TextBox)gvr.FindControl("txtNum"); //找到用来输入数量的TextBox控件 
            int count = Int32.Parse(otb.Text);//获得用户输入的数量值
            string BookID = gvr.Cells[1].Text;//得到该商品的ID代
            hashCar[BookID] = count;//更新hashTable表
        }
        Session["ShopCart"] = hashCar;//更新购物车
        Response.Redirect("shopCart.aspx");
    }
    protected void lnkbtnDelete_Command(object sender, CommandEventArgs e)
    {
        hashCar = (Hashtable)Session["ShopCart"];//获取其购物车
        //从Hashtable表中,将指定的商品从购物车中移除,其中,删除按钮(lnkbtnDelete)的CommandArgument参数值为商品ID代号
        hashCar.Remove(e.CommandArgument);
        Session["ShopCart"] = hashCar; //更新购物车
        Response.Redirect("shopCart.aspx");
    }
    protected void lnkbtnClear_Click(object sender, EventArgs e)
    {
        Session["ShopCart"] =null;
        Response.Redirect("shopCart.aspx");
    }
    protected void lnkbtnContinue_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }
    protected void lnkbtnCheck_Click(object sender, EventArgs e)
    {
        Response.Redirect("checkOut.aspx");
    }
    protected void gvShopCart_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvShopCart.PageIndex = e.NewPageIndex;
        bind();

    }
    protected void txtNum_TextChanged(object sender, EventArgs e)
    {
        hashCar = (Hashtable)Session["ShopCart"];  //获取其购物车
        foreach (GridViewRow gvr in this.gvShopCart.Rows)
        {

            TextBox otb = (TextBox)gvr.FindControl("txtNum"); //找到用来输入数量的TextBox控件 
            int count = Int32.Parse(otb.Text);//获得用户输入的数量值
            string BookID = gvr.Cells[1].Text;//得到该商品的ID代
            hashCar[BookID] = count;//更新hashTable表

        }
        Session["ShopCart"] = hashCar;//更新购物车
        bind();

    }

 

//shopcart.aspx

                        <table cellSpacing="0" cellPadding="0" width="95%" align="center" border="0" style="FONT-SIZE: 9pt">
                             <tr>
                             <td align="center">
                                <asp:Label ID="labMessage" runat="server" Visible="False"></asp:Label></td>
                            </tr>
                            <tr>
                             <td align="left" height =30px>
                                <asp:Label ID="labTotalPrice" runat="server" Text="0.00 " ></asp:Label>¥</td>
                            </tr>
                            <tr style =" font :9pt; font-family :宋体;"  valign =top >
                            <td align="left" style="height: 135px">
                            
                             <asp:GridView ID="gvShopCart" DataKeyNames ="BookID"   runat="server"  AutoGenerateColumns="False"  AllowPaging="True" OnPageIndexChanging="gvShopCart_PageIndexChanging" >
                                 <Columns>
                                     <asp:BoundField DataField="No" HeaderText="序号" ReadOnly="True">
                                         <ItemStyle HorizontalAlign="Center" />
                                         <HeaderStyle HorizontalAlign="Center" />
                                     </asp:BoundField>  
                                      <asp:BoundField DataField="BookID" HeaderText="书籍ID" ReadOnly="True">
                                         <ItemStyle HorizontalAlign="Center" />
                                         <HeaderStyle HorizontalAlign="Center" />
                                     </asp:BoundField>                                    
                                     <asp:BoundField DataField="BookName" HeaderText="书籍名称" ReadOnly="True">
                                      <ItemStyle HorizontalAlign="Center" />
                                      <HeaderStyle HorizontalAlign="Center" />
                                     </asp:BoundField>  
                                     <asp:TemplateField HeaderText="数量">
                                    <ItemTemplate >
                                       <asp:TextBox ID="txtNum" runat="server" Text =<%#Eval("Num") %> Width =60px  OnTextChanged="txtNum_TextChanged"></asp:TextBox>
                                       <asp:RegularExpressionValidator
                                ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtNum"
                                ErrorMessage="×" ValidationExpression="^\+?[1-9][0-9]*$"></asp:RegularExpressionValidator>
                                </ItemTemplate>
                                </asp:TemplateField>
                                   
                                     <asp:TemplateField HeaderText =单价>
                                         <HeaderStyle HorizontalAlign=Center />
                                         <ItemStyle HorizontalAlign =Center />
                                         <ItemTemplate >
                                            <%#Eval("price")%>¥
                                         </ItemTemplate>    
                                     </asp:TemplateField>
                                    <asp:TemplateField HeaderText =总价>
                                         <HeaderStyle HorizontalAlign=Center />
                                         <ItemStyle HorizontalAlign =Center />
                                         <ItemTemplate >
                                            <%#Eval("totalPrice")%>¥
                                         </ItemTemplate>    
                                     </asp:TemplateField>
                                     <asp:TemplateField>
                                         <HeaderStyle HorizontalAlign=Center />
                                         <ItemStyle HorizontalAlign =Center />
                                         <ItemTemplate >
                                             <asp:LinkButton ID="lnkbtnDelete" runat="server" CommandArgument ='<%#Eval("BookID") %>' OnCommand ="lnkbtnDelete_Command">删除</asp:LinkButton>
                                         </ItemTemplate>    
                                     </asp:TemplateField>
                                     
                                 </Columns>
                                </asp:GridView>
                            </td>
                            </tr>
                            <tr align =left valign =top  >
                                <td align="center"  >
                                    <asp:LinkButton ID="lnkbtnUpdate" runat="server" OnClick="lnkbtnUpdate_Click">更新购物车</asp:LinkButton>
                                    &nbsp;<asp:LinkButton ID="lnkbtnClear" runat="server" OnClick="lnkbtnClear_Click" >清空购物车</asp:LinkButton>
                                    <asp:LinkButton ID="lnkbtnContinue" runat="server" OnClick="lnkbtnContinue_Click" >继续购物</asp:LinkButton>  
                                    <asp:LinkButton ID="lnkbtnCheck" runat="server" OnClick="lnkbtnCheck_Click" >前往服务台</asp:LinkButton>
                                    </td>
                            </tr>
                            <tr>
                            <td align="left"  >
                                <br />
                                &nbsp;<li>如果要修改商品数量,请单击“更新购物车”按钮 &nbsp;&nbsp;&nbsp;</li>&nbsp;<li>如果要取消某个商品,请单击“删除”
                            <br />
                            </li>
                            </td>
                            </tr>
                        </table>

 

Default.aspx.cs //添加物品到购物车代码

    protected void dlDiscount_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "detailSee")
        {
            AddressBack(e);
        }
        else if (e.CommandName == "buy")
        {
            AddShopCart(e);
        } 

 

    }
    protected void dlHot_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "detailSee")
        {
            AddressBack(e);
        }
        else if (e.CommandName == "buy")
        {
            AddShopCart(e);
        }

    }
    /// <summary>
    /// 向购物车中添加新商品
    /// </summary>
    /// <param name="e">
    /// 获取或设置可选参数,
    /// 该参数与关联的 CommandName 
    /// 一起被传递到 Command 事件。
    /// </param> 
    public void AddShopCart(DataListCommandEventArgs e)
    {
        Hashtable hashCar;
        if (Session["ShopCart"] == null)
        {
            //如果用户没有分配购物车
            hashCar = new Hashtable();         //新生成一个
            hashCar.Add(e.CommandArgument, 1); //添加一个商品
            Session["ShopCart"] = hashCar;     //分配给用户
        }
        else
        {
            //用户已经有购物车
            hashCar = (Hashtable)Session["ShopCart"];//得到购物车的hash表
            if (hashCar.Contains(e.CommandArgument))//购物车中已有此商品,商品数量加1
            {
                int count = Convert.ToInt32(hashCar[e.CommandArgument].ToString());//得到该商品的数量
                hashCar[e.CommandArgument] = (count + 1);//商品数量加1
            }
            else
                hashCar.Add(e.CommandArgument, 1);//如果没有此商品,则新添加一个项
        }

    }

 

this.ClientScript.RegisterStartupScript(this.GetType(),"",<script>alert("商品添加成功!")</script>);

 

另附上一关于session实现购物车的视频讲解地址:http://www.itzcn.com/video-vid-251-spid-19.html

 

HashTable实现购物车, 

 

  先前我们的购物车使用的是数据库方式实现,每次购物都要进行数据库操作,很影响效率。现在我们采用HashTable和Session来实现购物车,这样便节省了数据库的操作,大大的提高效率 

1 private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)//假设前面购买命令是一个命令名为buy的LinkButton
   2 {//关键,建立和加如购物车
   3 string pid=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();//取出编号
   4 if(e.CommandName=="buy")//如果命令名是 buy,说明是购买
   5 {
6 if(Session["bus"]==null)//先就得检查购物车是否存在,如果不存在,就建立 
   7 {
8 System.Collections.Hashtable ht=new Hashtable();//先建立一个哈希表
   9 ht.Add(pid,1);//哈希表中的两个列,一个key,一个value ,key放编号,value放购买数量好了,预设置为1
  10 Session["bus"]=ht;//将哈希表赋值给Session对象
  11 }
12 else//如果存在的话
  13 {
14 Hashtable ht=(Hashtable)Session["bus"];//使用强制类型转换,再将Session["bus"]赋值给哈希表对象 ht
  15 if(ht[pid]==null)//如果哈希表中对应的ID没有,
  16 {
17 ht[pid]=1;//那就直接给他设为 1
  18 }
19 else//如果已经有对应的ID
  20 {
21 ht[pid]=(int)ht[pid]+1;//那么就把原来的取出来再加上 1
  22 }
23 Session["bus"]=ht;//最后再更新Session 对象
  24 }
25 }
26
27 } 

  而读取的方法如下: 

this.DataList1.DataSource=(Hashtable)Session["bus"];
this.DataList1.DataBind();
1private void LinkButton1_Click(object sender, System.EventArgs e)
2 {
3
4 foreach(DataListItem dl in this.DataList1.Items)//遍历集合
5 {
6 TextBox tb=(TextBox)dl.FindControl("TextBox1");//找到文本框
7 int newpid=Convert.ToInt32(tb.Text.ToString());//查出文本框里面的值
8
9 Label label1=(Label)dl.FindControl("key");//找到装载哈希表key字段的那个控件
10 string pid=label1.Text.ToString();//把他的值拿出来
11
12 Hashtable ht=(Hashtable)Session["bus"];//把session["bus"]对象赋值给哈希表 ht
13 int oldpid=(int)ht[pid];//求得原来的数量
14
15 if(newpid!=oldpid)//如果文本框里的值不等于原来的数量,就用新的更换到哈希表中的值
16 {
17 ht[pid]=newpid;
18 }
19 Session["bus"]=ht;//最后再更新Session 对象
20 }
21 } 

 

 

来自森大科技官方博客
http://www.cnsendblog.com/index.php/?p=338
GPS平台、网站建设、软件开发、系统运维,找森大网络科技!
http://cnsendnet.taobao.com

标签:收集,Session,DataColumn,hashCar,购物车,dtTable,ToString
来源: https://www.cnblogs.com/cnsend/p/12230917.html