asp.net 中购物车的两种存储方式 Session 和 Cookie 的应用实例 收藏 1.这是用 Cookie 存储的购物车的几种常用的操作: ///
/// 使用 Cookie 的购物车 /// public class CookieCar { public const string COOKIE_CAR = "Car"; //cookie 中的购物车 ///
/// 无参数的构造方法 /// public CookieCar() { } ///
/// 添加商品到购物车 /// ///
///
public void AddProductToCar(string id, string quantity) { string product = id + "," + quantity; //购物车中没有该商品 if (!VerDictCarIsExit(id)) { string oldCar = GetCarInfo(); string newCar = null; if (oldCar != "") { oldCar += "|"; } newCar += oldCar + product; AddCar(newCar); } else { int count = int.Parse(GetProductInfo(id).Split(',')[1].ToString()); UpdateQuantity(id, count + 1); } } ///
/// 添加商品的数量 /// ///
public void UpdateQuantity(string id, int quantity) { //得到购物车 string products = GetCarInfo(); products = "|" + products + "|"; string oldProduct = "|" + GetProductInfo(id) + "|"; if (products != "") { string oldCar = GetCarInfo(); string newProduct = "|" + id + "," + quantity + "|"; products = products.Replace(oldProduct, newProduct); products = products.TrimStart('|').TrimEnd('|'); AddCar(products); } } ///
/// 得到购物车 /// ///
public string GetCarInfo() { if (HttpContext.Current.Request.Cookies[COOKIE_CAR] != null) { return HttpContext.Current.Request.Cookies[COOKIE_CAR].Value.ToString(); } return ""; } ///
/// 根据ID 得到购物车中一种商品的信息 /// ///
///
private string GetProductInfo(string id) { string productInfo = null; //得到购物车中的所...