asp.net 使用cookie制作购物车

使用cookie制作购物车

思路:使用cookie存储产品ID和客户的订购量,其它的东西根据id值去库里面取

先看看cookie类,专门用于插入产品、更新订购量、删除产品

 

 

把产品添加到购物车的代码:

 

public class CCookieShoppingCart
{
    public CCookieShoppingCart()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static void AddToShoppingCart(int ProductID, int amount)
    {
        if (HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
        {
            HttpCookie oCookie = new HttpCookie("ShoppingCart");
            //Set Cookie to expire in 3 hours
            oCookie.Expires = DateTime.Now.AddHours(3);
            oCookie.Value = ProductID.ToString() + "*" + amount.ToString();

            HttpContext.Current.Response.Cookies.Add(oCookie);
        }
        //如果cookie已经存在
        else
        {
            bool bExists = false;
            char[] sep = { ',' };
            HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];
            //Set Cookie to expire in 3 hours
            oCookie.Expires = DateTime.Now.AddHours(3);
            //Check if Cookie already contain same item
            string sProdID = oCookie.Value.ToString();

            string[] arrCookie = sProdID.Split(sep);
            //查看cookie中是否有该产品
            string newCookie="";
            for (int i = 0; i < arrCookie.Length; i++)
            {
                //
                if (arrCookie[i].Length != 0)
                {
                    if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf('*')) == ProductID.ToString().Trim())
                    {
                        bExists = true;
                        //得到数量
                        string amountStr = arrCookie[i].Trim().Substring(arrCookie[i].Trim().IndexOf('*') + 1);
                        amountStr = (Convert.ToInt64(amountStr) + amount).ToString();
                        arrCookie[i] = arrCookie[i].Trim().Remove(arrCookie[i].IndexOf('*')) + "*" + amountStr;
                        newCookie = newCookie+","+arrCookie[i];
                    }
                }
            }

            //如果没有该产品
            if (!bExists)
            {
                if (oCookie.Value.Length == 0)
                {
                    oCookie.Value = ProductID.ToString() + "*" + amount.ToString();
                }
                else
                {
                    oCookie.Value = oCookie.Value + "," + ProductID.ToString() + "*" + amount.ToString();
                }
            }
            else
            {
                oCookie.Value = newCookie.Substring(1);
            }
           

            //Add back into  the HttpContext.Current.Response Objects.
            HttpContext.Current.Response.Cookies.Add(oCookie);
        }
    }
    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);
        }
    }

}

 

//为了方便我直接把id和订购量写死了

 CCookieShoppingCart.AddToShoppingCart(2,1)

购物车页面前台代码:

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:TemplateField HeaderText="ProductName">
                <ItemTemplate>
                    <%# DataBinder.Eval(Container.DataItem,"Counter") %>
                    . <a href="Product.aspx?+id=<%# DataBinder.Eval(Container.DataItem,"ProductID") %>">
                        <%# DataBinder.Eval(Container.DataItem,"ProductName") %></a>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="d">
                <ItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text=<%# DataBinder.Eval(Container.DataItem,"amount") %>></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="price">
                <ItemTemplate>
                <%# Eval("price") %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <a href="ShoppingCart.aspx?action=remove&id=<%# DataBinder.Eval(Container.DataItem,"ProductID") %>">
                        Remove</a> </td>
                </ItemTemplate>
            </asp:TemplateField>
            
        </Columns>
    </asp:GridView>

购物车页面后台代码:

 

protected void Page_Load(object sender, EventArgs e)
    {
        

        if (!IsPostBack)
        {
            BindData();
        }
    }
    private void BindData()
    {
        if (Request.Cookies["ShoppingCart"] != null)
        {
            HttpCookie oCookie = (HttpCookie)Request.Cookies["ShoppingCart"];
            string sProductID = oCookie.Value.ToString();
            if (sProductID.Length == 0)
            {
                lblMsg.Text = "<B>No items in your shopping cart<B><BR>";
            }
            else
            {
                char[] sep = { ',' };
                string[] sArrProdID = sProductID.Split(sep);

                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("ProductID"));
                dt.Columns.Add(new DataColumn("ProductName"));
                dt.Columns.Add(new DataColumn("Counter"));
                dt.Columns.Add(new DataColumn("amount"));
                dt.Columns.Add(new DataColumn("price"));

                int counter = 1;
                for (int i = 0; i < sArrProdID.Length; i++)
                {
                    DataTable dtt = DAL.product.getViewById(Convert.ToInt32(sArrProdID[i].ToString().Remove(sArrProdID[i].IndexOf('*'))));
                    DataRow dr = dt.NewRow();
                    dr["ProductID"] = sArrProdID[i].Remove(sArrProdID[i].IndexOf('*'));
                    dr["ProductName"] = dtt.Rows[0]["productname"].ToString();
                    dr["Counter"] = counter;
                    dr["amount"] = sArrProdID[i].Substring(sArrProdID[i].IndexOf('*')+1);
                    dr["price"] = dtt.Rows[0]["price"].ToString();
                    dt.Rows.Add(dr);
                    counter++;
                }
               

                GridView1.DataSource = dt;
                GridView1.DataBind();

                //GridView1.Columns[3].Visible = false;
            }
        }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET 中,可以使用 C# 代码基于 cookie 实现购物车功能,具体步骤如下: 1. 定义一个名为 "ShoppingCart" 的类,包含商品信息、数量、价格等属性。 ``` public class ShoppingCartItem { public int ProductId { get; set; } public string ProductName { get; set; } public decimal Price { get; set; } public int Quantity { get; set; } } ``` 2. 在添加商品到购物车时,将购物车信息保存到 cookie 中。 ``` public void AddToCart(int productId, string productName, decimal price, int quantity) { // 读取购物车信息 List<ShoppingCartItem> cart = GetShoppingCart(); // 查找商品是否已经存在于购物车中 ShoppingCartItem item = cart.FirstOrDefault(i => i.ProductId == productId); if (item == null) { // 商品不存在于购物车中,将其添加到购物车 item = new ShoppingCartItem { ProductId = productId, ProductName = productName, Price = price, Quantity = quantity }; cart.Add(item); } else { // 商品已经存在于购物车中,更新其数量 item.Quantity += quantity; } // 将购物车信息保存到 cookie 中 SaveShoppingCart(cart); } ``` 3. 从 cookie 中读取购物车信息。 ``` public List<ShoppingCartItem> GetShoppingCart() { List<ShoppingCartItem> cart = new List<ShoppingCartItem>(); HttpCookie cookie = HttpContext.Current.Request.Cookies["ShoppingCart"]; if (cookie != null) { string json = HttpUtility.UrlDecode(cookie.Value); cart = JsonConvert.DeserializeObject<List<ShoppingCartItem>>(json); } return cart; } ``` 4. 将购物车信息保存到 cookie 中。 ``` public void SaveShoppingCart(List<ShoppingCartItem> cart) { string json = JsonConvert.SerializeObject(cart); HttpCookie cookie = new HttpCookie("ShoppingCart", HttpUtility.UrlEncode(json)); HttpContext.Current.Response.Cookies.Add(cookie); } ``` 5. 在购物车页面中,读取购物车信息并显示出来。 ``` List<ShoppingCartItem> cart = GetShoppingCart(); foreach (ShoppingCartItem item in cart) { // 显示商品信息、数量、价格等 } ``` 注意,使用 cookie 实现购物车功能的缺点是,购物车信息存储在客户端,容易被篡改或删除。因此,对于重要的商业网站,建议使用服务器端的购物车实现方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值