WorldofASP.NET : ASP.NET Tutorial, Hosting, and Source Code
You are 1 of 203 users

WorldofASP.NET >> ASP.NET >> Applications

Building Simple Shopping Cart using ASP.NET and Cookies

This article will show you how you can build simple shopping cart with the help from Cookies

Published Date : 09 Dec 2007

Author : James Douglas
Language : VB.NET,C#
Platform : .NET
 
Technology : Visual Studio
Views : 7134
Rating : (3 votes so far)
Email to a Friend | Print this Article | Add to Favourites | Report Error

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




Other Related and Popular Articles :

Sending Email in ASP.NET 2.0
Send email in ASP.NET 2.0 Framework with or without SMTP Authentication
URL Rewriting with ASP.NET 2.0
How to implement URL Rewriting and Improve your SEO rankings.
Building a Photo Tagging Application using ASP.NET 2.0, LINQ, and Atlas
In this article, I will examines how to build a photo tagging application using ASP.NET 2.0, LINQ and Atlas framework.
Using LINQ to XML (and how to build a custom RSS Feed Reader with it)
In this article, Scott examines how to work with LINQ using XML. He also demonstrates how to build a custom RSS Feed Reader using these technologies.
Creating Contact Us Form easily using ASP.NET and SMTP
This article explain how to create a simple contact us form by using ASP.NET and System.Net.Mail to send email to the website owner
Build a DotNetNuke FileManager in ASP.NET
Tutorial and Code Sample on building a DotNetNuke FileManager in ASP.NET

Author Profile : James Douglas

I work in a Software House Company in Malaysia (Kuala Lumpur) and I am MCP Certified in C# and Web Application course.
I originally started my programming in Java but later on changed to Microsoft platform because of the simplicity and ease of use.
I love .NET programming and am doing it almost every day now.

Click here to view Author Profile


How would you rate the quality of this content?
Poor Excellent

Comments

#Thanks
14 Jul 2008 2:46 by : mohit gupta

Thanks for such a wonderful article...my interview is on third week of july and it'll help me a lot

#Shopping Cart Cookies
03 Jun 2008 7:36 by : asifiqbal

Your article was very help full for me.
There are about 6 Items in my cart
i make all of them in Cookies Including Item picture(path)
But the problem is to retrieve the 6 items
in the repeater.
will you please help me

Thanking you Advance.

#Can anyone help
16 Apr 2008 6:14 by : John Higgins

This code is excellent for my requirements but it would be fantastic if I could display my products in a drop-down box and also I would like to add a Quantity field. My ASP skills are limited so would be very greatful of anyones help.

Regards,

John

Leave New Comments


Article Content copyright by James Douglas
Everything else Copyright © by WorldofASP.NET 2008
 
Announcements
Earn Cash by writing an article or review
For more info Click here







Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 Link To Us | Contact Us
© 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | Windows Web Hosting | FREE ASP.NET CMS | Phone Card | PHP Directory | Bangkok Hotels |Calling Card