当前位置导航:炫浪网>>网络学院>>网页制作>>ASP.NET教程

自己写的一个asp.net-cookies购物车类

  自己写的一个asp.net cookies 购物车类,实现购物车功能,实现无需注册就可购物

  using System;

  using System.Data;

  using System.Configuration;

  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;

  //文章来源:http://study.pctoday.net.cn/2_ASP.net.aspx

  public class CookieShoppingCart

  {

  /// <summary>

  /// 加入购物车

  /// </summary>

  /// <param name="ProductID"></param>

  /// <param name="Quantity"></param>

  public static void AddToShoppingCart(int ProductID, int Quantity, int Box)

  {

  if (HttpContext.Current.Request.Cookies["ShoppingCart"] == null)

  {

  HttpCookie oCookie = new HttpCookie("ShoppingCart");

  //Set Cookie to expire in 3 hours

  oCookie.Expires = DateTime.Now.AddYears(3);

  oCookie.Value = ProductID.ToString() + ":" + Quantity.ToString() + ":" + Box.ToString();

  HttpContext.Current.Response.Cookies.Add(oCookie);

  }

  //如果cookie已经存在

  else

  {

  bool bExists = false;

  HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];

  oCookie.Expires = DateTime.Now.AddYears(3);

  string ShoppingCartStr = oCookie.Value.ToString();

  string[] arrCookie = ShoppingCartStr.Split(new char[] { ',' });

  //查看cookie中是否有该产品

  string newCookie = "";

  for (int i = 0; i < arrCookie.Length; i++)

  {

  if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) == ProductID.ToString().Trim())

  {

  bExists = true;

  string OldQuantity = arrCookie[i].Trim().Substring(arrCookie[i].Trim().IndexOf(':') + 1);//得到数量

  OldQuantity = OldQuantity.Remove(OldQuantity.LastIndexOf(":"));

  OldQuantity = (Convert.ToInt32(OldQuantity) + Quantity).ToString();

  arrCookie[i] = arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) + ":" + OldQuantity + ":" + Box.ToString();

  //HttpContext.Current.Response.Write(arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) + "已存在!数量:" + OldQuantity + "<br>");

  //HttpContext.Current.Response.Write(arrCookie[i] + "<br>");

  }

  newCookie = newCookie + "," + arrCookie[i];

  }

相关内容
赞助商链接