这篇文章给大家介绍c#中怎么利用Session对象实现一个购物车功能,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
创新互联基于成都重庆香港及美国等地区分布式IDC机房数据中心构建的电信大带宽,联通大带宽,移动大带宽,多线BGP大带宽租用,是为众多客户提供专业服务器托管报价,主机托管价格性价比高,为金融证券行业资阳服务器托管,ai人工智能服务器托管提供bgp线路100M独享,G口带宽及机柜租用的专业成都idc公司。
//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
|
|
|
|
|
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); } } ///
HashTable实现购物车,先前我们的购物车使用的是数据库方式实现,每次购物都要进行数据库操作,很影响效率。现在我们采用HashTable和Session来实现购物车,这样便节省了数据库的操作,大大的提高效率
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)//假设前面购买命令是一个命令名为buy的LinkButton{//关键,建立和加如购物车string pid=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();//取出编号if(e.CommandName=="buy")//如果命令名是 buy,说明是购买{if(Session["bus"]==null)//先就得检查购物车是否存在,如果不存在,就建立 {System.Collections.Hashtable ht=new Hashtable();//先建立一个哈希表ht.Add(pid,1);//哈希表中的两个列,一个key,一个value ,key放编号,value放购买数量好了,预设置为1Session["bus"]=ht;//将哈希表赋值给Session对象}else//如果存在的话{Hashtable ht=(Hashtable)Session["bus"];//使用强制类型转换,再将Session["bus"]赋值给哈希表对象 htif(ht[pid]==null)//如果哈希表中对应的ID没有,{ht[pid]=1;//那就直接给他设为 1}else//如果已经有对应的ID{ht[pid]=(int)ht[pid]+1;//那么就把原来的取出来再加上 1}Session["bus"]=ht;//最后再更新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 对象}}
关于c#中怎么利用Session对象实现一个购物车功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。