zoukankan      html  css  js  c++  java
  • [网络收集]asp.net中购物车的两种存储方式Session和Cookie的应用实例

    1.这是用Cookie存储的购物车的几种常用的操作:

    /// <summary>
    /// 使用Cookie的购物车
    /// </summary>
    public class CookieCar {
        public const string COOKIE_CAR = "Car";     //cookie中的购物车

        /// <summary>
        /// 无参数的构造方法
        /// </summary>
        public CookieCar() {
        }

        /// <summary>
        /// 添加商品到购物车
        /// </summary>
        /// <param name="id"></param>
        /// <param name="quantity"></param>
        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);
            }
        }

        /// <summary>
        /// 添加商品的数量
        /// </summary>
        /// <param name="id"></param>
        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);
            }
        }

        /// <summary>
        /// 得到购物车
        /// </summary>
        /// <returns></returns>
        public string GetCarInfo() {
            if (HttpContext.Current.Request.Cookies[COOKIE_CAR] != null) {
                return HttpContext.Current.Request.Cookies[COOKIE_CAR].Value.ToString();
            }
            return "";
        }

        /// <summary>
        /// 根据ID得到购物车中一种商品的信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string GetProductInfo(string id) {
            string productInfo = null;
            //得到购物车中的所有商品
            string products = GetCarInfo();
            foreach (string product in products.Split('|')) {
                if (id == product.Split(',')[0]) {
                    productInfo = product;
                    break;
                }
            }
            return productInfo;
        }

        /// <summary>
        /// 加入购物车  
        /// </summary>
        private void AddCar(string product) {
            HttpCookie car = new HttpCookie(COOKIE_CAR, product);
            car.Expires = DateTime.Now.AddDays(7);
            HttpContext.Current.Response.Cookies.Remove(COOKIE_CAR);
            HttpContext.Current.Response.Cookies.Add(car);
        }

        /// <summary>
        /// 判断商品是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool VerDictCarIsExit(string id) {
            //存在的标志: true 有, false 没有
            bool flag = false;
            //得到购物车中的所有商品
            string products = GetCarInfo();
            foreach (string product in products.Split('|')) {
                if (id == product.Split(',')[0]) {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        /// <summary>
        /// 通过商品编号删除订单
        /// </summary>
        /// <param name="id"></param>
        public void DeleteProduct(string id) {
            string oldProduct = GetProductInfo(id);
            oldProduct = "|"+oldProduct+"|";
            string products = GetCarInfo();
            if(products != "") {
                products = "|"+products+"|";
                products = products.Replace(oldProduct, "|");
                products = products.TrimStart('|').TrimEnd('|');
                AddCar(products);
            }
        }

        /// <summary>
        /// 晴空购物车
        /// </summary>
        public void ClearCar() {
            AddCar("");
        }

        /// <summary>
        /// 确认订单
        /// </summary>
        public void ConfirmOrder(System.Web.UI.Page page, double orderTotalPrice, User user) {
            //得到订单信息
            string products = GetCarInfo();
            if (products != "") {
                string message =null;
                if (ProductManager.OrderConfirm(products, orderTotalPrice, user, out message)) {
                    ClearCar();
                }
                Javascript.Alert(page, message, "Default.aspx");
            }
            else {
                Javascript.Alert(page, "订单为空,请选择商品!", "ProductList.aspx");
            }
        }
    }

    /// <summary>
        /// 得到购物车数据
        /// </summary>
        public DataSet GetCarData(GridView gv) {
            string carInfo = new CookieCar().GetCarInfo();
            if (carInfo != "") {
                string sql = "";
                foreach (string product in carInfo.Split('|')) {
                    int id = int.Parse(product.Split(',')[0].ToString());
                    int buyCount = int.Parse(product.Split(',')[1].ToString());
                    if (sql != "") {
                        sql += " union ";
                    }
                    sql += "select *, " + buyCount + " as buyCount, Price*" + buyCount + " as totalPrice from Products where Id = " + id;
                }
                TotalPrice(gv);       //计算总价
                return ProductManager.GetCarBySql(sql);
            }
            else {
                Javascript.GoError("购物车为空,请选择商品!");
            }
            return null;
        }

        /// <summary>
        /// 计算总价
        /// </summary>
        public double TotalPrice(GridView gv) {
            double totalCarPrice = 0d;
            foreach (GridViewRow row in gv.Rows) {
                int rowIndex = row.RowIndex;
                double totalPrice = double.Parse((gv.Rows[rowIndex].FindControl("lblTotalPrice") as Label).Text.ToString());
                totalCarPrice += totalPrice;
            }
            return totalCarPrice;
        }

    2.这是用Session存储的购物车:

    /// <summary>
    /// 使用Session的购物车
    /// </summary>
    public class SessionCar {
        private const string SESSION_CAR = "Car";

        /// <summary>
        /// 无参数的购物车
        /// </summary>
        public SessionCar() {
        }

        /// <summary>
        /// 添加商品到购物车
        /// </summary>
        public void AddCart(Product product) {
            if (HttpContext.Current.Session["CurrentUser"] != null) {
                if (HttpContext.Current.Session[SESSION_CAR] == null) {
                    BuildCart(product);
                }
                else {
                    DataTable cart = HttpContext.Current.Session[SESSION_CAR] as DataTable;
                    if (ExistProduct(cart, product.Id)) {
                        this.BuildSession(cart, product);
                    }
                }
                HttpContext.Current.Response.Redirect("Cart.aspx");
            }
            else {
                HttpContext.Current.Response.Redirect("Login.aspx");
            }
        }

        /// <summary>
        /// 已有产品
        /// </summary>
        /// <param name="cart"></param>
        /// <returns></returns>
        public bool ExistProduct(DataTable cart, int id) {
            foreach (DataRow dr in cart.Rows) {
                if (dr["Id"].ToString().Equals(id.ToString())) {
                    dr["buyCount"] = Convert.ToInt32(dr["buyCount"]) + 1;
                    HttpContext.Current.Session[SESSION_CAR] = cart;
                    HttpContext.Current.Response.Redirect("Cart.aspx");
                }
            }
            return true;
        }

        /// <summary>
        /// 新建购物车
        /// </summary>
        public void BuildCart(Product product) {
            DataTable cart = new DataTable();
            DataColumn[] dc = new DataColumn[] {
                new DataColumn("Id"),
                new DataColumn("Name"),
                new DataColumn("buyCount"),
                new DataColumn("Price"),
                new DataColumn("Picture"),
                new DataColumn("Number"),
                new DataColumn("SellNumber")
            };
            cart.Columns.AddRange(dc);
            BuildSession(cart, product);
        }

        /// <summary>
        /// 添加新商品
        /// </summary>
        /// <param name="cart"></param>
        public void BuildSession(DataTable cart, Product product) {
            DataRow dr = cart.NewRow();
            dr[0] = product.Id;
            dr[1] = product.Name;
            dr[2] = "1";
            dr[3] = product.Price;
            dr[4] = product.Picture;
            dr[5] = product.Number;
            dr[6] = product.SellNumber;
            cart.Rows.Add(dr);
            HttpContext.Current.Session[SESSION_CAR] = cart;
        }

    public DataTable GetCar() {
            if (HttpContext.Current.Session[SESSION_CAR] != null) {
                DataTable car = HttpContext.Current.Session[SESSION_CAR] as DataTable;
                return car;
            }
            else {
                return null;
            }
        }

        /// <summary>
        /// 计算总价
        /// </summary>
        /// <param name="cart"></param>
        public double TotalPrice(DataTable cart) {
            double total = 0;
            foreach (DataRow dr in cart.Rows) {
                total += Convert.ToDouble(dr["Price"]) * (Convert.ToInt32(dr[2].ToString()));
            }
            return total;
        }
    }

    摘自http://hi.baidu.com/devid_pitoushi/blog/item/44419339d18ae0cad4622537.html

  • 相关阅读:
    199. Binary Tree Right Side View
    [leetcode]leetcode初体验
    [项目]WebService涉及到的部分核心代码
    设计模式之简单工厂模式Simple Factory(四创建型)
    博客园利用Word发布博客功能[其他博客也可以如此使用]
    设计模式之单例模式Singleton(三创建型)
    设计模式之代理模式(二结构型)
    设计模式之策略模式(一对象行为型)
    Enterprise Achitect使用与类的关系的简单介绍
    2016年1月15日面试某互联网公司总结(二)
  • 原文地址:https://www.cnblogs.com/superfeeling/p/2362045.html
Copyright © 2011-2022 走看看