ASP.NET實例:利用對象序列化將購物車保存在Cookie中

購物車類:ShopCart.cs(說明:主要利用hashtable保存商品對象)

using System;
using System.Collections;

/// <summary>
/// 購物車類
/// </summary>
[Serializable]
public class ShopCart
{
public Hashtable _CartItems = new Hashtable();

/// <summary>
/// 構造函數
/// </summary>
public ShopCart()
{
///to do something
}


/// <summary>
/// 返回購物車中的所有商品(接口類型)
/// </summary>
public ICollection CartItems
{
get { return _CartItems.Values; }
}

/// <summary>
/// 購物中所有商品的價格合計
/// </summary>
public double Total
{
get
{
double sum = 0;
foreach (ShopCartItem item in _CartItems.Values)
{
sum += ((item.Price * item.Quantity) + item.SendPrice);
}
return sum;
}
}

/// <summary>
/// 返回購物車裏所有商品的數量
/// </summary>
public double TotalNum
{
get
{
double sum = 0;
foreach (ShopCartItem item in _CartItems.Values)
{
sum += item.Quantity;
}
return sum;
}
}

/// <summary>
/// 向購物車裏添加某商品
/// </summary>
/// <param name="ID">商品ID</param>
/// <param name="Name">商品名稱</param>
/// <param name="Price">商品單價</param>
/// <param name="AutoAddQuantity">如果購物車中已經存在該商品,該商品的數量是否加一,True數量加1,False數量不變</param>
public void AddItem(string ID, string Name, string DeliveryName, double Price, int Score, string ProductId, string PicUrl, double MarketPrice, double UserPrice, double VipPrice, double SendPrice,string ShopID, string UrlFrom, bool AutoAddQuantity)
{
ShopCartItem item = (ShopCartItem)_CartItems[ID];
if(item == null)
_CartItems.Add(ID, new ShopCartItem(ID, Name, DeliveryName, Price, Score, ProductId, PicUrl, MarketPrice, UserPrice, VipPrice, SendPrice,ShopID, UrlFrom));
else
{
if(AutoAddQuantity)
{
item.Quantity++;
}
_CartItems[ID] = item;
}
}

/// <summary>
/// 從購物車裏移除某商品
/// </summary>
/// <param name="ID">商品ID</param>
/// <param name="FullDelete">如果商品數量大於1,是否徹底從購物車中刪除該種商品,true徹底從購物車中刪除該種商品,false則僅將該種商品數量減一</param>
public void RemoveItem(string ID, bool FullDelete)
{
ShopCartItem item = (ShopCartItem)_CartItems[ID];
if(item == null)
{
return;
}
else
{
if(FullDelete)
{
_CartItems.Remove(ID);
}
else
{
item.Quantity--;
if(item.Quantity == 0)
{
_CartItems.Remove(ID);
}
else
{
_CartItems[ID] = item;
}
}
}
}

/// <summary>
/// 修改購物車裏某商品的數量
/// </summary>
/// <param name="ID">商品ID</param>
/// <param name="Quantity">商品數量</param>
public void UpdateItem(string ID, int Quantity)
{
ShopCartItem item = (ShopCartItem)_CartItems[ID];
if(item == null)
{
return;
}
else
{
if(Quantity > 0) //商品數量必須大於0
{
item.Quantity = Quantity;
}
_CartItems[ID] = item;
}
}


/// <summary>
/// 清空購物車
/// </summary>
public void ClearCart()
{
_CartItems.Clear();
}

}

/// <summary>
/// [購物車具體]商品類
/// </summary>
[Serializable]
public class ShopCartItem
{
private string _ID;//產品GUID
private string _Name;//產品名稱
private string _DeliveryName;//物流產品名
private double _Price=0;//產品單價(結算價格)
private int _Score = 0;//產品單個積分
private int _Quantity = 1;//產品數量
private string _ProductId;//產品自定義編號
private string _PicUrl;//圖片地址
private double _MarketPrice=0;//市場價格
private double _VipPrice=0;//VIp價格
private double _UserPrice=0;//會員價格
private double _SendPrice=0;//運輸費用
private string _ShopID;//商家ID
private string _UrlFrom; //頁面來源


/// <summary>
/// 屬性:商品ID
/// </summary>
public string ID
{
get { return _ID; }
}

/// <summary>
/// 屬性:商品名稱Name
/// </summary>
public string Name
{
get { return _Name; }
}

/// <summary>
/// 屬性:商品單價Price
/// </summary>
public double Price
{
get { return _Price; }
}

/// <summary>
/// 單件產品所獲積分
/// </summary>
public int Score
{
get
{
return _Score;
}
set
{
_Score = value;
}
}

/// <summary>
/// 產品編號
/// </summary>
public string ProductId
{
get
{
return _ProductId;
}
set
{
_ProductId = value;
}
}

/// <summary>
/// 產品圖片地址
/// </summary>
public string PicUrl
{
get
{
return _PicUrl;
}
set
{
_PicUrl = value;
}
}

/// <summary>
/// 市場價格
/// </summary>
public double MarketPrice
{
get
{
return _MarketPrice;
}

set
{
_MarketPrice = value;
}
}

/// <summary>
/// VIP價格
/// </summary>
public double VipPrice
{
get
{
return _VipPrice;
}

set
{
_VipPrice = value;
}
}

/// <summary>
/// 會員價格
/// </summary>
public double UserPrice
{
get
{
return _UserPrice;
}

set
{
_UserPrice = value;
}
}

/// <summary>
/// 運輸費用
/// </summary>
public double SendPrice
{
get
{
return _SendPrice;
}
set
{
_SendPrice = value;
}
}



/// <summary>
/// 屬性:商品數量Quantity
/// </summary>
public int Quantity
{
get { return _Quantity; }
set { _Quantity = value; }
}

/// <summary>
/// 商家ID
/// </summary>
public string ShopID {
get { return _ShopID; }
set { _ShopID = value; }
}

/// <summary>
/// 頁面來源
/// </summary>
public string UrlFrom
{
get { return _UrlFrom; }
set { _UrlFrom = value; }
}

/// <summary>
/// 購物車商品項完整構架函數
/// </summary>
/// <param name="ID">產品ID</param>
/// <param name="Name">產品名稱</param>
/// <param name="DeliveryName">產品物流名稱</param>
/// <param name="Price">產品單價(計算價)</param>
/// <param name="Score">產品積分</param>
/// <param name="ProductId">產品編號</param>
/// <param name="PicUrl">產品圖片</param>
/// <param name="MarketPrice">會員價格</param>
/// <param name="UserPrice">市場價格</param>
/// <param name="VipPrice">VIp價格</param>
/// <param name="SendPrice">運輸費用</param>
/// <param name="ShopID">商家ID</param>
/// <param name="UrlFrom">頁面來源</param>
public ShopCartItem(string ID, string Name, string DeliveryName, double Price, int Score, string ProductId, string PicUrl, double MarketPrice, double UserPrice, double VipPrice, double SendPrice, string ShopID, string UrlFrom)
{
_ID = ID;
_Name = Name;
_DeliveryName = DeliveryName;
_Quantity = 1;
_Price = Price;
_Score = Score;
_ProductId = ProductId;
_PicUrl = PicUrl;
_MarketPrice = MarketPrice;
_UserPrice = UserPrice;
_VipPrice = VipPrice;
_SendPrice = SendPrice;
_ShopID = ShopID;
_UrlFrom = UrlFrom;
}


/// <summary>
/// 購物車商品項簡單構架函數
/// </summary>
/// <param name="ID">產品ID</param>
/// <param name="Name">產品名稱</param>
/// <param name="Price">產品單價(計算價)</param>
public ShopCartItem(string ID, string Name, double Price)
{
_ID = ID;
_Name = Name;
_DeliveryName = "";
_Quantity = 1;
_Price = Price;
_Score = 0;
_ProductId = "";
_PicUrl = "";
_MarketPrice = 0;
_UserPrice = 0;
_VipPrice = 0;
_SendPrice = 0;
_ShopID = "";
_UrlFrom = "";
}

/// <summary>
/// 購物車商品項構架函數
/// </summary>
/// <param name="ID">產品ID</param>
/// <param name="Name">產品名稱</param>
/// <param name="Price">產品單價(計算價)</param>
/// <param name="UrlFrom">頁面來源</param>
public ShopCartItem(string ID, string Name, double Price,string UrlFrom)
{
_ID = ID;
_Name = Name;
_DeliveryName = "";
_Quantity = 1;
_Price = Price;
_Score = 0;
_ProductId = "";
_PicUrl = "";
_MarketPrice = 0;
_UserPrice = 0;
_VipPrice = 0;
_SendPrice = 0;
_ShopID = "";
_UrlFrom = UrlFrom;
}


/// <summary>
/// 購物車商品項標準構架函數
/// </summary>
/// <param name="ID">產品ID</param>
/// <param name="Name">產品名稱</param>
/// <param name="Price">產品單價(計算價)</param>
/// <param name="UrlFrom">頁面來源</param>
/// <param name="UrlFrom">頁面來源</param>
public ShopCartItem(string ID, string Name, double Price,string ShopID, string UrlFrom)
{
_ID = ID;
_Name = Name;
_DeliveryName = "";
_Quantity = 1;
_Price = Price;
_Score = 0;
_ProductId = "";
_PicUrl = "";
_MarketPrice = 0;
_UserPrice = 0;
_VipPrice = 0;
_SendPrice = 0;
_ShopID = ShopID;
_UrlFrom = UrlFrom;
}
}



測試頁面:Demo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Demo.aspx.cs" Inherits="Public_Test_Demo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label><br />
<br />
<asp:Button ID="btnReadCookie" runat="server" Text="讀取Cookie中的ShopCart" onClick="btnReadCookie_Click" />&nbsp;</div>
</form>
</body>
</html>

後置代碼Demo.aspx.cs文件:

using System;
using System.Collections;
using System.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Text;
using CNTVS.TOOLS;

public partial class Public_Test_Demo : System.Web.UI.Page
{
string CookieName = "ShopCart";

protected void Page_Load(object sender, EventArgs e)
{


if (!IsPostBack)
{
ShopCart SC = new ShopCart();
SC.AddItem("1", "ProductName", "ProductName", 0, 0, "ProductID", "", 0, 0, 0, 0, "ShopId", "TestUrl", true);
SC.AddItem("2", "ProductName123", "ProductName123", 0, 0, "ProductID123", "", 0, 0, 0, 0, "ShopId111", "TestUrl23", true);

//將ShopCart對象寫入Cookie
IFormatter fm = new BinaryFormatter();
Stream sm = new MemoryStream();
fm.Serialize(sm, SC);
sm.Seek(0, SeekOrigin.Begin);
StreamReader reader = new StreamReader(sm);
string strCart = reader.ReadToEnd();
reader.Close();
HttpCookie hc = new HttpCookie(CookieName);
hc.Value = Server.UrlEncode(strCart);
hc.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(hc);
}
}


///// <summary>
///// 將ShopCart寫入Cookie
///// </summary>
///// <param name="SC">ShopCart對象</param>
///// <param name="CookieName">CookieName,默認爲ShopCart</param>
//public static string ShopCartToCookie(ShopCart SC, string CookieName)
//{
// if (Utils.CheckNull(CookieName)) { CookieName = "ShopCart"; }
// if (Utils.CheckNull(SC))
// {
// Utils.WriteCookie(CookieName, "");
// return "";
// }
// else
// {
// IFormatter fm = new BinaryFormatter();
// Stream sm = new MemoryStream();
// fm.Serialize(sm, SC);
// sm.Seek(0, SeekOrigin.Begin);
// StreamReader reader = new StreamReader(sm);
// string strCart = reader.ReadToEnd();
// reader.Close();
// Utils.WriteCookie(CookieName, strCart);
// return strCart;
// }
//}


///// <summary>
///// 將Cookie反序列化爲ShopCart
///// </summary>
///// <param name="CookieName">CookieName,默認爲ShopCart</param>
//public static ShopCart CookieToShopCart(string CookieName)
//{
// if (Utils.CheckNull(CookieName)) { CookieName = "ShopCart"; }
// string StrCart = Utils.GetCookie(CookieName);
// if (Utils.CheckNull(StrCart))
// {
// return null;
// }

// byte[] bt = System.Text.Encoding.Default.GetBytes(StrCart);
// Stream sm = new MemoryStream(bt);
// IFormatter fm = new BinaryFormatter();
// ShopCart SC = (ShopCart)fm.Deserialize(sm);
// if (Utils.CheckNull(SC))
// {
// return null;
// }
// else
// {
// return SC;
// }
//}


protected void btnReadCookie_Click(object sender, EventArgs e)
{
string StrCartNew = Server.UrlDecode(Request.Cookies[CookieName].Value.ToString());
byte[] bt = System.Text.Encoding.Default.GetBytes(StrCartNew);
Stream smNew = new MemoryStream(bt);
IFormatter fmNew = new BinaryFormatter();
ShopCart SCNew = (ShopCart)fmNew.Deserialize(smNew);
foreach(ShopCartItem SCI in SCNew.CartItems)
{
lblResult.Text += "<br/>產品名稱:" + SCI.Name;
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章