您好,登錄后才能下訂單哦!
這篇文章主要為大家詳細介紹了Session對象實現購物車功能的方法,文中示例代碼介紹的非常詳細,零基礎也能參考此文章,感興趣的小伙伴們可以參考一下。
//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" >
<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" >
<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>);
另附上一關于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 }
看完這篇文章,你們學會用Session對象實現購物車功能的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。