使用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;
            }
        }
posted on 2009-02-14 11:48  草原和大树  阅读(5027)  评论(6编辑  收藏  举报