這篇文章給大家介紹c#中怎么利用Session對象實(shí)現(xiàn)一個購物車功能,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
創(chuàng)新互聯(lián)基于成都重慶香港及美國等地區(qū)分布式IDC機(jī)房數(shù)據(jù)中心構(gòu)建的電信大帶寬,聯(lián)通大帶寬,移動大帶寬,多線BGP大帶寬租用,是為眾多客戶提供專業(yè)服務(wù)器托管報(bào)價,主機(jī)托管價格性價比高,為金融證券行業(yè)資陽服務(wù)器托管,ai人工智能服務(wù)器托管提供bgp線路100M獨(dú)享,G口帶寬及機(jī)柜租用的專業(yè)成都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) { //如果沒有購物,則給出相應(yīng)信息,并隱藏按鈕 this.labMessage.Text = "您還沒有購物!"; this.labMessage.Visible = true; //顯示提示信息 this.lnkbtnCheck.Visible = false; //隱藏“前往服務(wù)臺”按鈕 this.lnkbtnClear.Visible = false; //隱藏“清空購物車”按鈕 this.lnkbtnContinue.Visible = false; //隱藏“繼續(xù)購物”按鈕 } else { hashCar = (Hashtable)Session["ShopCart"]; //獲取其購物車 if (hashCar.Count == 0) { //如果沒有購物,則給出相應(yīng)信息,并隱藏按鈕 this.labMessage.Text = "您購物車中沒有商品!"; this.labMessage.Visible = true; //顯示提示信息 this.lnkbtnCheck.Visible = false; //隱藏“前往服務(wù)臺”按鈕 this.lnkbtnClear.Visible = false; //隱藏“清空購物車”按鈕 this.lnkbtnContinue.Visible = false; //隱藏“繼續(xù)購物”按鈕 } else { //設(shè)置購物車內(nèi)容的數(shù)據(jù)源 dtTable = new DataTable(); DataColumn column1 = new DataColumn("No"); //序號列 DataColumn column2 = new DataColumn("BookID"); //書籍ID代號 DataColumn column3 = new DataColumn("BookName"); //書籍名稱 DataColumn column4 = new DataColumn("Num"); //數(shù)量 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; //對數(shù)據(jù)表中每一行進(jìn)行遍歷,給每一行的新列賦值 //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); } //計(jì)算價格 DataTable dstable; int i = 1; float price;//商品單價 int count; //商品數(shù)量 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; //計(jì)算合價 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) { //如果沒有購物,則給出相應(yīng)信息,并隱藏按鈕 this.labMessage.Text = "您還沒有購物!"; this.labMessage.Visible = true; //顯示提示信息 this.lnkbtnCheck.Visible = false; //隱藏“前往服務(wù)臺”按鈕 this.lnkbtnClear.Visible = false; //隱藏“清空購物車”按鈕 this.lnkbtnContinue.Visible = false; //隱藏“繼續(xù)購物”按鈕 } else { hashCar = (Hashtable)Session["ShopCart"]; //獲取其購物車 if (hashCar.Count == 0) { //如果沒有購物,則給出相應(yīng)信息,并隱藏按鈕 this.labMessage.Text = "您購物車中沒有商品!"; this.labMessage.Visible = true; //顯示提示信息 this.lnkbtnCheck.Visible = false; //隱藏“前往服務(wù)臺”按鈕 this.lnkbtnClear.Visible = false; //隱藏“清空購物車”按鈕 this.lnkbtnContinue.Visible = false; //隱藏“繼續(xù)購物”按鈕 } else { //設(shè)置購物車內(nèi)容的數(shù)據(jù)源 dtTable = new DataTable(); DataColumn column1 = new DataColumn("No"); //序號列 DataColumn column2 = new DataColumn("BookID"); //書籍ID代號 DataColumn column3 = new DataColumn("BookName"); //書籍名稱 DataColumn column4 = new DataColumn("Num"); //數(shù)量 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; //對數(shù)據(jù)表中每一行進(jìn)行遍歷,給每一行的新列賦值 foreach (object key in hashCar.Keys) { row = dtTable.NewRow(); row["BookID"] = key.ToString(); row["Num"] = hashCar[key].ToString(); dtTable.Rows.Add(row); } //計(jì)算價格 DataTable dstable; int i = 1; float price;//商品單價 int count; //商品數(shù)量 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; //計(jì)算合價 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語句,遍歷更新購物車中的商品數(shù)量 foreach (GridViewRow gvr in this.gvShopCart.Rows) { TextBox otb = (TextBox)gvr.FindControl("txtNum"); //找到用來輸入數(shù)量的TextBox控件 int count = Int32.Parse(otb.Text);//獲得用戶輸入的數(shù)量值 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參數(shù)值為商品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"); //找到用來輸入數(shù)量的TextBox控件 int count = Int32.Parse(otb.Text);//獲得用戶輸入的數(shù)量值 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實(shí)現(xiàn)購物車,先前我們的購物車使用的是數(shù)據(jù)庫方式實(shí)現(xiàn),每次購物都要進(jìn)行數(shù)據(jù)庫操作,很影響效率。現(xiàn)在我們采用HashTable和Session來實(shí)現(xiàn)購物車,這樣便節(jié)省了數(shù)據(jù)庫的操作,大大的提高效率
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)//假設(shè)前面購買命令是一個命令名為buy的LinkButton{//關(guān)鍵,建立和加如購物車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放購買數(shù)量好了,預(yù)設(shè)置為1Session["bus"]=ht;//將哈希表賦值給Session對象}else//如果存在的話{Hashtable ht=(Hashtable)Session["bus"];//使用強(qiáng)制類型轉(zhuǎn)換,再將Session["bus"]賦值給哈希表對象 htif(ht[pid]==null)//如果哈希表中對應(yīng)的ID沒有,{ht[pid]=1;//那就直接給他設(shè)為?。眪else//如果已經(jīng)有對應(yīng)的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];//求得原來的數(shù)量 if(newpid!=oldpid)//如果文本框里的值不等于原來的數(shù)量,就用新的更換到哈希表中的值{ht[pid]=newpid;}Session["bus"]=ht;//最后再更新Session 對象}}
關(guān)于c#中怎么利用Session對象實(shí)現(xiàn)一個購物車功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。