时间:2021-05-20
本文实现了c# Session对象实现购物车的方法,分享给大家,也给自己留个笔记:
//shopcart.aspx.csusing 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> <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 /> <li>如果要修改商品数量,请单击“更新购物车”按钮 </li> <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>);HashTable实现购物车,先前我们的购物车使用的是数据库方式实现,每次购物都要进行数据库操作,很影响效率。现在我们采用HashTable和Session来实现购物车,这样便节省了数据库的操作,大大的提高效率
而读取的方法如下:
this.DataList1.DataSource=(Hashtable)Session["bus"];this.DataList1.DataBind();1private void LinkButton1_Click(object sender, System.EventArgs e){ foreach(DataListItem dl in this.DataList1.Items)//遍历集合{TextBox tb=(TextBox)dl.FindControl("TextBox1");//找到文本框int newpid=Convert.ToInt32(tb.Text.ToString());//查出文本框里面的值 Label label1=(Label)dl.FindControl("key");//找到装载哈希表key字段的那个控件string pid=label1.Text.ToString();//把他的值拿出来 Hashtable ht=(Hashtable)Session["bus"];//把session["bus"]对象赋值给哈希表 htint oldpid=(int)ht[pid];//求得原来的数量 if(newpid!=oldpid)//如果文本框里的值不等于原来的数量,就用新的更换到哈希表中的值{ht[pid]=newpid;}Session["bus"]=ht;//最后再更新Session 对象}}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了asp.net基于session实现购物车的方法。分享给大家供大家参考,具体如下://加入购物车protectedvoidLinkButton2_
//购物车session的产生代码if(!$session&&!$scid){/*session用来区别每一个购物车,相当于每个车的身份证号;scid只用来标识
if(!$session&&!$scid){/*session用来区别每一个购物车,相当于每个车的身份证号;scid只用来标识一个购物车id号,可以看做是每个车
本文实例讲述了php利用cookies实现购物车的方法。分享给大家供大家参考。具体分析如下:php购物车是在电子商务网站会用到的,一种像超市购物车一样的,选好商
本文实例为大家分享了java实现购物车功能的具体代码,供大家参考,具体内容如下1需要实现1、实现淘淘商城的购物车功能2购物车功能2.1功能说明1、商品加入购物车