一个购物车的简单实现(多层开发)

 转自  http://www.dotnetbips.com/0D82BC51-AB67-4F5F-AB04-CD461CE5E910.aspx?articleid=280


  今天在老外的网上发现个写的不错的多层实现的构物车...

      代码如下......

     CCookieShoppingCart.cs  //用 cookie
using System;
using System.Web;
using System.Collections;

namespace ShoppingCartGeneric
{
    
public class CCookieShoppingCart:IShoppingCart
    
{

        
public int Add(string cartid, IShoppingCartItem item)
        
{
            HttpCookie c
=null;
            
if(HttpContext.Current.Request.Cookies["shoppingcart"]==null)
                c
=new HttpCookie("shoppingcart");
            
else
                c
=HttpContext.Current.Request.Cookies["shoppingcart"];
            
string itemdetails;
            itemdetails
=item.ProductID + "|" + item.ProductName + "|" + item.UnitPrice;
            c.Values[item.ProductID.ToString()]
=itemdetails;
            HttpContext.Current.Response.Cookies.Add(c);
            
return 1;
        }


        
public int Remove(string cartid, IShoppingCartItem item)
        
{
            HttpCookie c
=HttpContext.Current.Request.Cookies["shoppingcart"];
            c.Values.Remove(item.ProductID.ToString());
            HttpContext.Current.Response.Cookies.Add(c);
            
return 1;
        }


        
public ArrayList GetItems(string cartid)
        
{
            HttpCookie c
=HttpContext.Current.Request.Cookies["shoppingcart"];
            ArrayList items
=new ArrayList();

            
for(int i=0;i<c.Values.Count;i++)
            
{
                
string[] vals=c.Values[i].Split('|');
                CShoppingCartItem item
=new CShoppingCartItem();
                item.ProductID
=int.Parse(vals[0]);
                item.ProductName
=vals[1];
                item.UnitPrice
=decimal.Parse(vals[2]);
                item.Quantity
=1;

                items.Add(item);
            }

            
return items;
        }


    }

}


CDatabaseShoppingCart.cs  //用数据库

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;

namespace ShoppingCartGeneric
{
    
public class CDatabaseShoppingCart:IShoppingCart
    
{
        
private static string connstr=@"data source=.\vsdotnet;initial catalog=northwind;user id=sa";

        
public int Add(string cartid, IShoppingCartItem item)
        
{
            SqlConnection cnn
=new SqlConnection(connstr);
            SqlCommand cmd
=new SqlCommand();
            cmd.Connection
=cnn;
            cmd.CommandText
="insert into ShoppingCart_Products(cartid,productid,productname,unitprice,quantity) values(@cartid,@prodid,@prodname,@unitprice,@qty)";

            SqlParameter p1
=new SqlParameter("@cartid",cartid);
            SqlParameter p2
=new SqlParameter("@prodid",item.ProductID);
            SqlParameter p3
=new SqlParameter("@prodname",item.ProductName);
            SqlParameter p4
=new SqlParameter("@unitprice",item.UnitPrice);
            SqlParameter p5
=new SqlParameter("@qty",item.Quantity);

            cmd.Parameters.Add(p1);
            cmd.Parameters.Add(p2);
            cmd.Parameters.Add(p3);
            cmd.Parameters.Add(p4);
            cmd.Parameters.Add(p5);

            cnn.Open();
            cmd.ExecuteNonQuery();
            cnn.Close();

            
return 0;
        }


        
public void UpdateQuantity(string cartid,int productid,int newqty)
        
{
            SqlConnection cnn
=new SqlConnection(connstr);
            SqlCommand cmd
=new SqlCommand();
            cmd.Connection
=cnn;
            cmd.CommandText
="update ShoppingCart_Products set quantity=@qty where cartid=@cartid and productid=@prodid";

            SqlParameter p1
=new SqlParameter("@qty",newqty);
            SqlParameter p2
=new SqlParameter("@cartid",cartid);
            SqlParameter p3
=new SqlParameter("@prodid",productid);

            cmd.Parameters.Add(p1);
            cmd.Parameters.Add(p2);
            cmd.Parameters.Add(p3);

            cnn.Open();
            cmd.ExecuteNonQuery();
            cnn.Close();

        }


        
public int Remove(string cartid, IShoppingCartItem item)
        
{
            SqlConnection cnn
=new SqlConnection(connstr);
            SqlCommand cmd
=new SqlCommand();
            cmd.Connection
=cnn;
            cmd.CommandText
="delete from ShoppingCart_Products where cartid=@cartid and productid=@prodid";

            SqlParameter p1
=new SqlParameter("@cartid",cartid);
            SqlParameter p2
=new SqlParameter("@prodid",item.ProductID);

            cmd.Parameters.Add(p1);
            cmd.Parameters.Add(p2);

            cnn.Open();

            cmd.ExecuteNonQuery();

            cnn.Close();
            
return 0;
        }


        
public System.Collections.ArrayList GetItems(string cartid)
        
{
            SqlDataAdapter da
=new SqlDataAdapter("select * from ShoppingCart_Products where cartid='" + cartid + "'",connstr);
            DataSet ds
=new DataSet();
            da.Fill(ds,
"shoppingcart");    
            
            ArrayList arr
=new ArrayList();
            
foreach(DataRow row in ds.Tables[0].Rows)
            
{
                CShoppingCartItem item
=new CShoppingCartItem();
                item.ProductID
=(int)row["productid"];
                item.ProductName
=(String)row["productname"];
                item.Quantity
=(int)row["quantity"];
                item.UnitPrice
=(Decimal)row["unitproce"];
                arr.Add(item);
            }

            
return arr;
        }


    }

}


   CSessionShoppingCart.cs //用 session
using System;
using System.Collections;
using System.Web;

namespace ShoppingCartGeneric
{
    
/// <summary>
    
/// Summary description for CSessionShoppingCart.
    
/// </summary>

    public class CSessionShoppingCart:IShoppingCart
    
{

        
public int Add(string cartid, IShoppingCartItem item)
        
{
            ArrayList arr;
            
if(HttpContext.Current.Session["mycart"]!=null)
            
{
                arr
=(ArrayList)HttpContext.Current.Session["mycart"];
            }

            
else
            
{
                arr
=new ArrayList();
                HttpContext.Current.Session[
"mycart"]=arr;
            }

            arr.Add(item);
            
return 0;
        }


        
public int Remove(string cartid, IShoppingCartItem item)
        
{
            ArrayList items
=(ArrayList)HttpContext.Current.Session["mycart"];
            
for(int i=0;i<items.Count;i++)
            
{
                
if(((IShoppingCartItem)items[i]).ProductID==item.ProductID)
                
{
                    items.RemoveAt(i);
                    
break;
                }

            }

            
return 0;
        }


        
public System.Collections.ArrayList GetItems(string cartid)
        
{
            
return (ArrayList)HttpContext.Current.Session["mycart"];
        }

    }

}


CShoppingCart.cs  //基类

using System;

namespace ShoppingCartGeneric
{
    
public enum CShoppingCartType
    
{
        Cookie,Session,Database
    }


    
public class CShoppingCart:IShoppingCart
    
{
        
private IShoppingCart cart=null;

        
public CShoppingCart(CShoppingCartType type)
        
{
            
switch(type)
            
{
                
case CShoppingCartType.Cookie:
                    cart
=new CCookieShoppingCart();
                    
break;
                
case CShoppingCartType.Session:
                    cart
=new CSessionShoppingCart();
                    
break;
                
case CShoppingCartType.Database:
                    cart
=new CDatabaseShoppingCart();
                    
break;
            }

        }


        
public int Add(string cartid, IShoppingCartItem item)
        
{
            
return cart.Add(cartid,item);
        }


        
public int Remove(string cartid, IShoppingCartItem item)
        
{
            
return cart.Remove(cartid,item);
        }


        
public System.Collections.ArrayList GetItems(string cartid)
        
{
            
return cart.GetItems(cartid);
        }


    }

}



   IShoppingCart.cs   接口
using System;

namespace ShoppingCartGeneric
{
    
public class CShoppingCartItem:IShoppingCartItem
    
{
        
private int intProductID;
        
private string strProductName;
        
private decimal decUnitPrice;
        
private int intQuantity;

        
public int ProductID
        
{
            
get
            
{
                
return intProductID;
            }

            
set
            
{
                intProductID
=value;
            }

        }


        
public string ProductName
        
{
            
get
            
{
                
return strProductName;
            }

            
set
            
{
                strProductName
=value;
            }

        }


        
public decimal UnitPrice
        
{
            
get
            
{
                
return decUnitPrice;
            }

            
set
            
{
                decUnitPrice
=value;
            }

        }


        
public int Quantity
        
{
            
get
            
{
                
return intQuantity;
            }

            
set
            
{
                intQuantity
=value;
            }

        }


    }

}


productcatalog.aspx.cs  //调用页 用户选择


cart.Add(Session.SessionID,item);

//这个 Session.SessionID 不知道作者为什么加这个,,在客个基类中都没有调用...
你把它改成其它的.也一样正常执行.......
可能是多用户时用 session 类时,用它作用户判断确定唯一性,可是我查过资料,每个 session 生成时都有一个唯一的  sessionid 啊......清楚的朋友谈谈......


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Security.Principal;

namespace ShoppingCartGeneric
{
    
public class WebForm1 : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Button Button1;
        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
if(!Page.IsPostBack)
            
{
                BindGrid();
            }

        }



        
private void BindGrid()
        
{
            SqlDataAdapter da
=new SqlDataAdapter("select * from products",@"data source=.\vsdotnet;initial catalog=northwind;user id=sa");
            DataSet ds
=new DataSet();
            da.Fill(ds,
"products");

            DataGrid1.DataSource
=ds;
            DataGrid1.DataBind();
        }


        
#region Web Form Designer generated code
        
override protected void OnInit(EventArgs e)
        
{
            
//
            
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
            
//
            InitializeComponent();
            
base.OnInit(e);
        }

        
        
/// <summary>
        
/// Required method for Designer support - do not modify
        
/// the contents of this method with the code editor.
        
/// </summary>

        private void InitializeComponent()
        
{    
            
this.DataGrid1.SelectedIndexChanged += new System.EventHandler(this.DataGrid1_SelectedIndexChanged);
            
this.Button1.Click += new System.EventHandler(this.Button1_Click);
            
this.Load += new System.EventHandler(this.Page_Load);

        }

        
#endregion


        
private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e)
        
{
            CShoppingCart cart
=new CShoppingCart(CShoppingCartType.Cookie);
            CShoppingCartItem item
=new CShoppingCartItem();
            item.ProductID
=int.Parse(DataGrid1.SelectedItem.Cells[1].Text);
            item.ProductName
=DataGrid1.SelectedItem.Cells[2].Text;
            item.UnitPrice
=decimal.Parse(DataGrid1.SelectedItem.Cells[3].Text);
            item.Quantity
=1;
            
            cart.Add(Session.SessionID,item);
        }


        
private void Button1_Click(object sender, System.EventArgs e)
        
{
            Response.Redirect(
"cart.aspx");
        }

    }

}


<%@ Page language="c#" Codebehind="productcatalog.aspx.cs" AutoEventWireup="false" Inherits="ShoppingCartGeneric.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    
<HEAD>
        
<title>WebForm1</title>
        
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        
<meta name="CODE_LANGUAGE" Content="C#">
        
<meta name="vs_defaultClientScript" content="JavaScript">
        
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    
</HEAD>
    
<body MS_POSITIONING="GridLayout">
        
<form id="Form1" method="post" runat="server">
            
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 72px" runat="server"
                BorderColor
="#CC9966" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4"
                AutoGenerateColumns
="False" Width="448px">
                
<SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66"></SelectedItemStyle>
                
<ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle>
                
<HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
                
<FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle>
                
<Columns>
                    
<asp:ButtonColumn Text="Select" CommandName="Select"></asp:ButtonColumn>
                    
<asp:BoundColumn DataField="productid" HeaderText="Product ID"></asp:BoundColumn>
                    
<asp:BoundColumn DataField="productname" HeaderText="Product Name"></asp:BoundColumn>
                    
<asp:BoundColumn DataField="unitprice" HeaderText="Unit Price"></asp:BoundColumn>
                    
<asp:ButtonColumn Text="Select" CommandName="Select"></asp:ButtonColumn>
                
</Columns>
                
<PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC"></PagerStyle>
            
</asp:DataGrid><asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 32px" runat="server"
                Text
="Show Cart"></asp:Button>
        
</form>
    
</body>
</HTML>

//购物车

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace ShoppingCartGeneric
{
    
/// <summary>
    
/// Summary description for cart.
    
/// </summary>

    public class cart : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Button Button1;
        
protected System.Web.UI.WebControls.Button Button2;
        
protected System.Web.UI.WebControls.Label Label3;
        
protected System.Web.UI.WebControls.Label lblAmt;
        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
if(!Page.IsPostBack)
            
{
                FillCartFromSession();
            }

        }


        
private void FillCartFromSession()
        
{
            CShoppingCart cart
=new CShoppingCart(CShoppingCartType.Cookie);
            ArrayList items
=(ArrayList)cart.GetItems(Session.SessionID);
            DataGrid1.DataSource
=items;
            DataGrid1.DataBind();
            Button1_Click(
null,null);
        }


        
#region Web Form Designer generated code
        
override protected void OnInit(EventArgs e)
        
{
            
//
            
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
            
//
            InitializeComponent();
            
base.OnInit(e);
        }

        
        
/// <summary>
        
/// Required method for Designer support - do not modify
        
/// the contents of this method with the code editor.
        
/// </summary>

        private void InitializeComponent()
        
{    
            
this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_DeleteCommand);
            
this.DataGrid1.SelectedIndexChanged += new System.EventHandler(this.DataGrid1_SelectedIndexChanged);
            
this.Button1.Click += new System.EventHandler(this.Button1_Click);
            
this.Button2.Click += new System.EventHandler(this.Button2_Click);
            
this.Load += new System.EventHandler(this.Page_Load);

        }

        
#endregion


        
private void Button1_Click(object sender, System.EventArgs e)
        
{
            
decimal total=0;

            
try
            
{
                
foreach(DataGridItem dgi in DataGrid1.Items)
                
{
                    
if(dgi.ItemType==ListItemType.Item || dgi.ItemType==ListItemType.AlternatingItem)
                    
{
                        TextBox t
=(TextBox)dgi.Cells[3].Controls[1];
                        
int quantity=int.Parse(t.Text);
                        
decimal unitprice=Decimal.Parse(dgi.Cells[2].Text);
                        total
=total + (unitprice * quantity);

                        
//************************
                        
//Only for database shopping cart
                        
//IShoppingCart cart=new CShoppingCart(CShoppingCartType.Database);
                        
//((CDatabaseShoppingCart)cart).UpdateQuantity(Session.SessionID,int.Parse(dgi.Cells[0].Text),quantity);
                        
//************************
                    }

                }

            }

            
catch
            
{
            }


            lblAmt.Text
=total.ToString();
        }


        
private void Button2_Click(object sender, System.EventArgs e)
        
{
            
//now you can iterate through cookies collection
            
//and DataGrid and get details of all items
            
//then add your code here to insert into database
        }


        
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        
{
            CShoppingCart cart
=new CShoppingCart(CShoppingCartType.Cookie);
            CShoppingCartItem item
=new CShoppingCartItem();
            item.ProductID
=int.Parse(e.Item.Cells[0].Text);
            cart.Remove(Session.SessionID,item);
            FillCartFromSession();
        }


        
private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e)
        
{
        
        }

    }

}



<%@ Page language="c#" Codebehind="cart.aspx.cs" AutoEventWireup="false" Inherits="ShoppingCartGeneric.cart" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    
<HEAD>
        
<title>cart</title>
        
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        
<meta name="CODE_LANGUAGE" Content="C#">
        
<meta name="vs_defaultClientScript" content="JavaScript">
        
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    
</HEAD>
    
<body>
        
<form id="Form1" method="post" runat="server">
            
<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="100%" border="0">
                
<TR>
                    
<TD><asp:DataGrid id="DataGrid1" runat="server" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
                            BackColor
="White" CellPadding="4" AutoGenerateColumns="False" Width="100%">
                            
<SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66"></SelectedItemStyle>
                            
<ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle>
                            
<HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
                            
<FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle>
                            
<Columns>
                                
<asp:BoundColumn DataField="productid" HeaderText="Product ID"></asp:BoundColumn>
                                
<asp:BoundColumn DataField="productname" HeaderText="Product Name"></asp:BoundColumn>
                                
<asp:BoundColumn DataField="unitprice" HeaderText="Unit Price"></asp:BoundColumn>
                                
<asp:TemplateColumn HeaderText="Quantity">
                                    
<ItemTemplate>
                                        
<asp:TextBox id=TextBox2 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.quantity") %>' Columns="3">
                                        
</asp:TextBox>
                                    
</ItemTemplate>
                                    
<EditItemTemplate>
                                        
<asp:TextBox id=TextBox1 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.quantity") %>'>
                                        
</asp:TextBox>
                                    
</EditItemTemplate>
                                
</asp:TemplateColumn>
                                
<asp:ButtonColumn Text="Delete" CommandName="Delete"></asp:ButtonColumn>
                            
</Columns>
                            
<PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC"></PagerStyle>
                        
</asp:DataGrid></TD>
                
</TR>
                
<TR>
                    
<TD align="center"><asp:Label id="Label3" runat="server" Font-Bold="True">Total Amount :</asp:Label><asp:Label id="lblAmt" runat="server" Font-Bold="True"></asp:Label></TD>
                
</TR>
                
<TR>
                    
<TD align="center"><asp:Button id="Button1" runat="server" Text="Recalculate"></asp:Button></TD>
                
</TR>
                
<TR>
                    
<TD align="center"><asp:Button id="Button2" runat="server" Text="Place Order"></asp:Button></TD>
                
</TR>
            
</TABLE>
        
</form>
    
</body>
</HTML>

posted on 2005-06-14 21:09  gwazy  阅读(9297)  评论(11编辑  收藏  举报

导航