62,046
社区成员
发帖
与我相关
我的任务
分享
public class CardShop {
public static String CookieName = "SHOPPING_INFO";
/// <summary>
/// 添加商品进购物车
/// </summary>
/// <param name="productId"></param>
/// <param name="num"></param>
/// <returns></returns>
public static bool AddProduct(int productId, int num) {
HttpCookie hc = null;
String oldCookieValue;
String NewValue;
hc = HttpContext.Current.Request.Cookies[CookieName];
if (hc == null) //如果Cookie不存在 则直接新建Cookie 保存商品id和数量;
{
hc = new HttpCookie(CookieName);
hc.Expires = DateTime.Now.AddDays(7);
hc.Value = productId.ToString() + "|" + num.ToString();
}
else //假设Cookie存在 则处理
{
oldCookieValue = hc.Value;
NewValue = AddCookieValue(oldCookieValue, productId, num);
hc.Value = NewValue;
}
HttpContext.Current.Response.AppendCookie(hc);
//Cookie写入Response
return true; //结束
}
/// <summary>
/// 已存在Cookie则追加商品
/// </summary>
/// <param name="Value"></param>
/// <param name="NewProductId"></param>
/// <param name="Num"></param>
private static string AddCookieValue(string Value, int NewProductId, int Num) {
String NewValue = "";
bool IsAdd = false;
string[] productList = Value.Split(',');
for (int i = 0; i < productList.Length; i++) {
string[] productInfo = productList[i].Split('|');
if (productInfo[0] == NewProductId.ToString()) {
IsAdd = true;
NewValue += productInfo[0] + "|" + ((int.Parse(productInfo[1])) + Num).ToString() + ",";
}
else {
NewValue += productInfo[0] + "|" + productInfo[1] + ",";
}
}
if (IsAdd) {
NewValue = NewValue.Substring(0, NewValue.Length - 1);
}
else {
NewValue += NewProductId.ToString() + "|" + Num.ToString();
}
return NewValue;
}
/// <summary>
/// 获取购物车信息
/// </summary>
/// <returns></returns>
public static string GetShoppingInfo() {
HttpCookie hc = null;
hc = HttpContext.Current.Request.Cookies[CookieName];
if (hc == null) //如果Cookie存在 则直接新建Cookie 保存商品id和数量;
{
return null;
}
else {
return hc.Value;
}
}
}
public static void RemoveShoppingCart(int ProductID)
{
if (HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
{
//Do nothing
}
else
{
HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];
//Set Cookie to expire in 3 hours
char[] sep = { '|' };
oCookie.Expires = DateTime.Now.AddHours(3);
//Check if Cookie already contain same item
string sProdID = oCookie.Value.ToString();
string[] arrCookie = sProdID.Split(sep);
string[] arrCookie2 = new string[arrCookie.Length - 1];
int j = 0;
for (int i = 0; i < arrCookie.Length; i++)
{
if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf('*')) != ProductID.ToString())
{
arrCookie2[j] = arrCookie[i];
j++;
}
}
string sCookieID = "";
for (int i = 0; i < arrCookie2.Length; i++)
{
sCookieID = sCookieID + arrCookie2[i] + "|";
}
if (sCookieID.Length > 0)
{
oCookie.Value = sCookieID.Substring(0, sCookieID.Length - 1);
}
else
{
oCookie.Value = "";
}
//Add back into the HttpContext.Current.Response Objects.
HttpContext.Current.Response.Cookies.Add(oCookie);
}