Tuesday, October 21, 2008

Building Simple Shopping Cart using ASP.NET and Cookies

Building Simple Shopping Cart using ASP.NET and CookiesThis article will show you how you can build simple shopping cart with the help from Cookies

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 ShopH2>

<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 Carta>TD>
TR>
ITEMTEMPLATE>
<FOOTERTEMPLATE>
table>
FOOTERTEMPLATE>
ASP:REPEATER>
<BR />
<A href="ShoppingCart.aspx">My Shopping CartA>

<BR />


<A href="Checkout.aspx">CheckOutA>
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") %>">
RemoveA>TD>
TR>
ITEMTEMPLATE>
ASP:REPEATER>
TABLE>
<BR />
<A HREF='Product.aspx'>Continue ShoppingA>
<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


7 comments:

Anonymous said...

hello i cant seem to download your zip file it redirects me to another websit

Diploma Student said...

Can u please provide another new link to download the zip file? thx in advance

saranya said...

Read all the information that i've given in above article. It'll give u the whole idea about it.
python training in chennai
python course in chennai
python training in bangalore

jai said...

Fantastic work! This is the type of information that should follow collective approximately the web. Embarrassment captivating position Google for not positioning this transmit higher! Enlarge taking place greater than and visit my web situate
Data Science course in Chennai
Data science course in bangalore
Data science course in pune
Data science online course
Data Science Interview questions and answers
Data Science Tutorial

rohini said...

Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up. 
Best Devops Training in pune
Devops Training in Bangalore
Microsoft azure training in Bangalore
Power bi training in Chennai

nisha said...

The Blog is very Impressive. every concept of this blog was very clearly explained, easily able to understand for the every concept.

Data Science Training Course In Chennai | Data Science Training Course In Anna Nagar | Data Science Training Course In OMR | Data Science Training Course In Porur | Data Science Training Course In Tambaram | Data Science Training Course In Velachery

rocky said...

After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information. thank you for more information.
python training in chennai

python online training in chennai

python training in bangalore

python training in hyderabad

python online training

python flask training

python flask online training

python training in coimbatore