本文實(shí)例講述了C#基于cookie實(shí)現(xiàn)的購(gòu)物車(chē)。分享給大家供大家參考,具體如下:
下面的代碼將商品添加到cookie中,這里就不再編寫(xiě)添加商品到購(gòu)物車(chē)的頁(yè)面流程,而是直接使用代碼實(shí)現(xiàn)
HttpCookie cookie = new HttpCookie("shop");//cookie.values集合能夠存儲(chǔ)多個(gè)鍵值對(duì),其中add方法的第一個(gè)參數(shù)是商品編號(hào),第二個(gè)參數(shù)是商品名稱(chēng)和價(jià)格,中間用都好分隔。cookie.Values.Add("1", "電腦,2000");cookie.Values.Add("2", "電視,2200");cookie.Values.Add("3", "冰箱,2300");cookie.Expires = DateTime.Now.AddDays(1);Response.Cookies.Add(cookie);好,上面已經(jīng)將購(gòu)買(mǎi)的商品添加到購(gòu)物車(chē)中。其中使用了cookie的values集合,第一個(gè)參數(shù)是商品編號(hào),第二個(gè)參數(shù)是商品名稱(chēng)和價(jià)格。
第二步是顯示購(gòu)物車(chē)
/// <summary>/// 顯示購(gòu)物車(chē)/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Button2_Click(object sender, EventArgs e){ LoadShop();}//顯示購(gòu)物車(chē)private void LoadShop(){ //首先判斷名稱(chēng)為"shop"的cookie是否存在 if (Request.Cookies["shop"] != null) { HttpCookie cookie = Request.Cookies["shop"]; StringBuilder sb = new StringBuilder(); sb.Append("<table>"); //便利此cookie的values集合,取出每一個(gè)鍵值對(duì) for (int i = 0; i < cookie.Values.Count; i++) { sb.Append("<tr>"); sb.Append("<td>"); sb.Append("<a href=WebForm5.aspx?id=" + cookie.Values.AllKeys[i] + ">刪除<a/>"); sb.Append("</td>"); sb.Append("<td>"); //獲取每個(gè)鍵值對(duì)中的值 string[] shops = cookie.Values[i].Split(','); //獲取商品名稱(chēng) sb.Append("<td>" + shops[0] + "</td>"); //獲取商品價(jià)格 sb.Append("<td>" + shops[1] + "</td>"); sb.Append("</td>"); sb.Append("</tr>"); } sb.Append("</table>"); mydiv.InnerHtml = sb.ToString(); }}其中注釋已經(jīng)寫(xiě)的很清楚了。
第三步是刪除購(gòu)物車(chē)中商品
protected void Page_Load(object sender, EventArgs e){ if (!IsPostBack) { if (!string.IsNullOrEmpty(Request.QueryString["id"])) { string id = Request.QueryString["id"]; DeleteShop(id); } }}private void DeleteShop(string id){ if (Request.Cookies["shop"] != null) { HttpCookie cookie = Request.Cookies["shop"]; cookie.Values.Remove(id); if (cookie.Values.Count == 0) { cookie.Expires = DateTime.Now.AddDays(-1); } Response.Cookies.Add(cookie); LoadShop(); }}希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選