Introduction
This article will show you on building a simple shopping cart for your e-commerce store by using ASP.NET and Cookies. No database is needed for storing the shopping cart. I am choosing cookies to store the shopping cart rather than database because of the performance reason and also because Shopping Cart normally is used only for storing the temporary data. Your user might or might not continue with the payment. So to save hassle on cleaning the temporary table all the time, Using cookies can help you on this. You can set the cookies expire date to be one or two hour or even one day from now. So that when your customer came back tomorrow, you still have the basket ready.
Building Shopping Cart using ASP.NET and Cookies
In this article, we will be using the Northwind Database as the Product backend. If you don't have the database, you can do a Google search for this sample database provided by Microsoft.
First, lets open your Visual Studio 2005 and Add two File called ShoppingCart.aspx, and another one called Product.aspx
In the Product.aspx, we will be populating products from Northwind Database, and then later on you can add the items into your shopping basket.
In the ShoppingCart.aspx, we will be populating the Shopping Basket from the Cookies. We are storing the ProductID into Cookies as a comma separated product.
Below is the screenshot for both of the Page
1. Product.aspx

2. ShoppingCart.aspx

Source Code for Product.aspx
<H2>My E-Commerce Shop</H2>
<ASP:REPEATER ID="rptProducts" RUNAT="server">
<HEADERTEMPLATE>
<TABLE BORDER=1>
</HEADERTEMPLATE>
<ITEMTEMPLATE>
<TR>
<TD>
<%#DataBinder.Eval(Container.DataItem,"ProductName") %>
</TD>
<TD><a HREF='ShoppingCart.aspx?action=add&ID=<%#DataBinder.Eval(Container.DataItem,"ProductID") %>'>
Add to Shopping Cart</a></TD>
</TR>
</ITEMTEMPLATE>
<FOOTERTEMPLATE>
</table>
</FOOTERTEMPLATE>
</ASP:REPEATER>
<BR />
<A href="ShoppingCart.aspx">My Shopping Cart</A>
<BR />
<A href="Checkout.aspx">CheckOut</A>
For the Product.aspx, we just add one Repeater Control and we just do a basic binding to a Products table.
The Code behind for Product.aspx
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"].Trim());
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from products where supplierid = 2";
SqlDataReader dr = cmd.ExecuteReader();
rptProducts.DataSource = dr;
rptProducts.DataBind();
dr.Close();
conn.Close();
}
For the ShoppingCart.aspx, We also add a Repeater Control that will bind itself to the Cookies. <TABLE BORDER="1" WIDTH="80%" CELLPADDING="0" CELLSPACING="0">
<TR>
<TD COLSPAN="2">
<ASP:LABEL ID="lblMsg" RUNAT="server"></ASP:LABEL>
</TD>
</TR>
<ASP:REPEATER ID="rptShoppingCart" RUNAT="server">
<ITEMTEMPLATE>
<TR>
<TD>
<%# DataBinder.Eval(Container.DataItem,"Counter") %>
.
<%# DataBinder.Eval(Container.DataItem,"ProductName") %>
</TD>
<TD>
<A HREF="ShoppingCart.aspx?action=remove&id=<%# DataBinder.Eval(Container.DataItem,"ProductID") %>">
Remove</A></TD>
</TR>
</ITEMTEMPLATE>
</ASP:REPEATER>
</TABLE>
<BR />
<A HREF='Product.aspx'>Continue Shopping</A>
<BR />
<A HREF=''>Check Out </A>
Add to ShoppingCart Method Code Snippet
private void AddToShoppingCart(int ProductID)
{
if (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();
Response.Cookies.Add(oCookie);
}
else
{
bool bExists = false;
char[] sep = { ',' };
HttpCookie oCookie = (HttpCookie)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);
for (int i = 0; i < arrCookie.Length; i++)
{
if (arrCookie[i].Trim() == ProductID.ToString().Trim())
{
bExists = true;
}
}
if (!bExists)
{
if (oCookie.Value.Length == 0)
{
oCookie.Value = ProductID.ToString();
}
else
{
oCookie.Value = oCookie.Value + "," + ProductID;
}
}
//Add back into the Response Objects.
Response.Cookies.Add(oCookie);
}
}
Remove ShoppingCart Method Code Snippet
if (Request.Cookies["ShoppingCart"] == null)
{
//Do nothing
}
else
{
HttpCookie oCookie = (HttpCookie)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() != 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 Response Objects.
Response.Cookies.Add(oCookie);
Now, let me explain the Logic behind the Add ShoppingCart Method. Basically we create a new Cookie Object and then we set the Cookies Expiry to be 3 hours from now. So that Customer Shopping Cart will still be there during 3 hours time. We also prevent duplicate item being added into the Shopping Cart.
Everytime, when you adding or editing the Cookie Value, please Remember to add back the cookies into the Response.Cookies collection or else the cookie will not get written to the client browser. And if you like to remove the Cookies, You can actually set the Cookie Expire Date to be less than Now().
Conclusion
In this example, I just provide a very basic Shopping Cart functionality. But my whole point is to give you an idea on how to build a Shopping Cart by utilizing Cookies. You can actually improve the code by adding extra features such as Quantity. It is entirely up to you to make your shopping cart as easy to use as possible. Thats' all for now. Happy Coding in ASP.NET
Download Source Code