ASP.NET Shopping Cart Tutorial

Version 1.0

2011 Summer

Overview

This is a Book Shopping Cart using ASP.NET with Microsoft Access 2007 Database.

Visitors can browse several books.

When cart is empty, it will remind you to add products.

They can add each book to their cart by click the book image:

They can review their cart, editing the number of books they want and removing any items they no longer want:

After click Checkout button, it will show the following.

1. File -> New Website

We’ll start by selecting “New Website” from the File menu in Visual Studio 2010. This brings up the New Project dialog.

We’ll select the ASP.NET Empty Web Site. Name your project and press the OK button.

First, We’ll add three folders in the Solution Explorer on the right side. App_Code folder, App_Data folder and Images folder. Right Click on the Project Name and Choose add ASP.NET folder.

/App_Data – This folder holds our database files.

/App_Code – This folder holds all of our custom classes. These classes will automatically be accessible from the code in any of our pages.

/Images – This folder holds the pictures of books.

Next, We’ll configure the Microsoft Access Database. Right Click on the DataConnections which in the Server Explore. Add Connection…

On the Data source, click the Change button.. Then choose Microsoft Access Database File, and Click Ok.

In the Database file name, we will choose our Access database file by click Browse button and Test Connection.

We’ll add the access file into App_Data folder.

Code:

ShoppingCart.cs in App_Code folder

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

using System.Collections.Generic;

namespace ShoppingCart

{

/// <summary>

/// Summary description for ShoppingCart

/// </summary>

[Serializable]

public class CartItem

{

private int _productID;

private string _productName;

private string _imageUrl;

private int _quantity;

private double _price;

private double _subTotal;

public CartItem()

{

}

public CartItem(int ProductID, string ProductName, string ImageUrl, int Quantity, double Price)

{

_productID = ProductID;

_productName = ProductName;

_imageUrl = ImageUrl;

_quantity = Quantity;

_price = Price;

_subTotal = Quantity * Price;

}

public int ProductID

{

get

{

return _productID;

}

set

{

_productID = value;

}

}

public string ProductName

{

get { return _productName; }

set { _productName = value; }

}

public string ImageUrl

{

get { return _imageUrl; }

set { _imageUrl = value; }

}

public int Quantity

{

get { return _quantity; }

set { _quantity = value; }

}

public double Price

{

get { return _price; }

set { _price = value; }

}

public double SubTotal

{

get { return _quantity * _price; }

}

}

[Serializable]

public class Cart

{

private DateTime _dateCreated;

private DateTime _lastUpdate;

private ListCartItem> _items;

public Cart()

{

if (this._items == null)

{

this._items = new ListCartItem>();

this._dateCreated = DateTime.Now;

}

}

public ListCartItem> Items

{

get { return _items;}

set { _items = value;}

}

public void Insert(int ProductID, double Price, int Quantity, string ProductName, string ImageUrl)

{

int ItemIndex = ItemIndexOfID(ProductID);

if (ItemIndex == -1)

{

CartItem NewItem = new CartItem();

NewItem.ProductID = ProductID;

NewItem.Quantity = Quantity;

NewItem.Price = Price;

NewItem.ProductName = ProductName;

NewItem.ImageUrl = ImageUrl;

_items.Add(NewItem);

}

else

{

_items[ItemIndex].Quantity += 1;

}

_lastUpdate = DateTime.Now;

}

public void Update(int RowID, int ProductID, int Quantity, double Price)

{

CartItem Item = _items[RowID];

Item.ProductID = ProductID;

Item.Quantity = Quantity;

Item.Price = Price;

_lastUpdate = DateTime.Now;

}

public void DeleteItem(int rowID)

{

_items.RemoveAt(rowID);

_lastUpdate = DateTime.Now;

}

private int ItemIndexOfID(int ProductID)

{

int index = 0;

foreach (CartItem item in _items)

{

if (item.ProductID == ProductID)

{

return index;

}

index += 1;

}

return -1;

}

public double Total

{

get

{

double t = 0;

if (_items == null)

{

return 0;

}

foreach (CartItem Item in _items)

{

t += Item.SubTotal;

}

return t;

}

}

}

}

Product.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Products.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

html xmlns="http://www.w3.org/1999/xhtml">

head runat="server">

titleProducts</title

</head

body

form id="form1" runat="server">

div

asp:AccessDataSource ID="AccessDataSource1" runat="server"

DataFile="~/App_Data/book.accdb"

SelectCommand="SELECT [ImageUrl], [ProductName], [Price], [ProductID] FROM [books]">

</asp:AccessDataSource

</div

asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1" RepeatColumns="3"

RepeatDirection="Horizontal" DataKeyField="ProductID">

ItemTemplate

asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# Eval("ImageUrl", "Images\\thumb_{0}") %>' PostBackUrl='<%# Eval("ProductID", "ProductDetails.aspx?ProductID={0}") %>' /<br />

asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' /<br />

asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price") %>' /> br />

br />

br />

</ItemTemplate

</asp:DataList

br />

asp:HyperLink ID="CartLink" runat="server" NavigateUrl="~/UserCart.aspx">View Shopping Cart</asp:HyperLinkbr />

&nbsp;br />

.br />

</form

</body

</html

ProductDetails.aspx, this page is used for showing details for selected book from product catalog page.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ProductDetails.aspx.cs" Inherits="ProductDetails" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

html xmlns="http://www.w3.org/1999/xhtml"

head runat="server">

titleProduct Details</title

</head

body

form id="form1" runat="server">

div

asp:AccessDataSource ID="AccessDataSource1" runat="server"

DataFile="~/App_Data/book.accdb"

SelectCommand="SELECT ProductID, ImageUrl, ProductName, Authors, Publisher, ISBN, Copyright, Price FROM books WHERE (ProductID = ?)">

SelectParameters

asp:QueryStringParameter Name="ProductID" QueryStringField="ProductID" Type="Decimal" />

</SelectParameters

</asp:AccessDataSource

</div

asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1">

ItemTemplate

asp:Image ID="Image1" runat="server"

ImageUrl='<%# Eval("ImageUrl","~/Images\\{0}") %>' />

asp:Label ID="ImageUrlLabel" runat="server" Text='<%# Eval("ImageUrl") %>' Visible="False" />

br />

asp:Label ID="ProductNameLabel" runat="server"

Text='<%# Eval("ProductName") %>' />

br />

asp:Label ID="AuthorsLabel" runat="server" Text='<%# Eval("Authors") %>' />

br />

asp:Label ID="PublisherLabel" runat="server" Text='<%# Eval("Publisher") %>' />

br />

asp:Label ID="ISBNLabel" runat="server" Text='<%# Eval("ISBN") %>' />

br />

asp:Label ID="CopyrightLabel" runat="server" Text='<%# Eval("Copyright") %>' />

br />

asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price") %>' />

br />

br />

</ItemTemplate

</asp:DataListbr/>

asp:Button ID="btnAdd" runat="server" OnClick="Button1_Click" Text="Add to Cart" /<br />

br />

&nbsp;asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Products.aspx">Return to Products Page</asp:HyperLink

</form

</body

</html

Write this code in C# code behind of ProductDetails.aspx page

protected void Button1_Click(object sender, EventArgs e)

{

double Price = double.Parse(((Label)DataList1.Controls[0].FindControl("PriceLabel")).Text);

string ProductName = ((Label)DataList1.Controls[0].FindControl("ProductNameLabel")).Text;

string ProductImageUrl = ((Label)DataList1.Controls[0].FindControl("ImageUrlLabel")).Text;

int ProductID = int.Parse(Request.QueryString["ProductID"]);

if (Profile.SCart == null)

{

Profile.SCart = new ShoppingCart.Cart();

}

Profile.SCart.Insert(ProductID, Price, 1, ProductName, ProductImageUrl);

Server.Transfer("Products.aspx");

}

Now right click on solution explorer and add new web user control, name itCartControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CartControl.ascx.cs" Inherits="CartControl" %>

asp:GridView ID="grdCart" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" OnRowCancelingEdit="grdCart_RowCancelingEdit" OnRowDeleting="grdCart_RowDeleting" OnRowEditing="grdCart_RowEditing" OnRowUpdating="grdCart_RowUpdating">

Columns

asp:TemplateField

ItemTemplate

asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ImageUrl", "~/Images/thumb_{0}") %>' />

</ItemTemplate

</asp:TemplateField

asp:BoundField DataField="ProductName" HeaderText="Product" ReadOnly="True" />

asp:BoundField DataField="Quantity" HeaderText="Quantity" />

asp:BoundField DataField="Price" DataFormatString="{0:c}" HeaderText="Price" ReadOnly="True" />

asp:BoundField DataField="SubTotal" DataFormatString="{0:c}" HeaderText="Total"

ReadOnly="True" />

asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />

</Columns

EmptyDataTemplate

Your Shopping Cart is empty, add items

a href="Products.aspx">Add Products</a

</EmptyDataTemplate

</asp:GridView

asp:Label ID="TotalLabel" runat="server"</asp:Label

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

asp:Button ID="Button1" runat="server" onclick="Button1_Click"

Text="Checkout" />

Openweb.configfile and add this section for enabling anonymous users to add items to cart

connectionStrings

add name="ConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; DataSource=~\App_Data\book.accdb" providerName="System.Data.OleDb"/>

</connectionStrings

system.web

authorization

allow users="?"/>

allow roles="admin"/>

</authorization

roleManager enabled="true"/>

authentication mode="Forms"/>

system.web

anonymousIdentification enabled="true"/>

profile enabled="true"

properties

add name="SCart" serializeAs="Binary" type="ShoppingCart.Cart" allowAnonymous="true"/>

</properties

</profile

</system.web

Now go to code behind of CartControl.ascx and write this code

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using ShoppingCart;

public partial class CartControl : System.Web.UI.UserControl

{

protected void Page_Load(object sender, EventArgs e)

{

if (Profile.SCart == null)

{

Profile.SCart = new ShoppingCart.Cart();

}

if (!Page.IsPostBack)

{

ReBindGrid();

}

if(Profile.SCart.Items == null)

{

TotalLabel.Visible = false;

}

}

protected void grdCart_RowEditing(object sender, GridViewEditEventArgs e)

{

grdCart.EditIndex = e.NewEditIndex;

ReBindGrid();

}

protected void grdCart_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

TextBox txtQuantity = (TextBox)grdCart.Rows[e.RowIndex].Cells[2].Controls[0];

int Quantity = Convert.ToInt32(txtQuantity.Text);

if (Quantity == 0)

{

Profile.SCart.Items.RemoveAt(e.RowIndex);

}

else

{

Profile.SCart.Items[e.RowIndex].Quantity = Quantity;

}

grdCart.EditIndex = -1;

ReBindGrid();

}

protected void grdCart_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

grdCart.EditIndex = -1;

ReBindGrid();

}

protected void grdCart_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

Profile.SCart.Items.RemoveAt(e.RowIndex);

ReBindGrid();

}

private void ReBindGrid()

{

grdCart.DataSource = Profile.SCart.Items;

DataBind();

TotalLabel.Text = string.Format("The Amount is:{0,19:C}", Profile.SCart.Total);

}

protected void Button1_Click(object sender, EventArgs e)

{

Session["Total"] = TotalLabel.Text;

Response.Redirect("Checkout.aspx");

}

}

AddGlobal Application Class (Global.asax)by right clicking on solution explorer -> add new Item. And write code mentioned below in it.

void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs e)

{

ProfileCommon anonymousProfile = Profile.GetProfile(e.AnonymousID);

if (anonymousProfile.SCart != null)

{

if (Profile.SCart == null)

Profile.SCart = new ShoppingCart.Cart();

Profile.SCart.Items.AddRange(anonymousProfile.SCart.Items);

anonymousProfile.SCart = null;

}

ProfileManager.DeleteProfile(e.AnonymousID);

AnonymousIdentificationModule.ClearAnonymousIdentifier();

}

Add another webform and name itUserCart.aspx,

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserCart.aspx.cs" Inherits="UserCart" %>

<%@ Register Src="CartControl.ascx" TagName="CartControl" TagPrefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

html xmlns="http://www.w3.org/1999/xhtml"

head runat="server">

titleUntitled Page</title

</head

body

form id="form1" runat="server">

div

uc1:CartControl ID="CartControl1" runat="server" />

br />

br />

asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Products.aspx">Return to Products Page</asp:HyperLink</div

</form

</body

</html

Checkout.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Checkout.aspx.cs" Inherits="Checkout" %>

<%@ Register Src="CartControl.ascx" TagName="CartControl" TagPrefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

html xmlns="http://www.w3.org/1999/xhtml">

head runat="server">

title</title

style type="text/css">

.style1

{

font-size: xx-large;

color: #0066FF;

}

.style2

{

text-align: center;

}

</style

</head

body

form id="form1" runat="server">

div class="style2">

strongspan class="style1">

br />

br />

br />

Congratulations! Your order has been placed!

</span

asp:Label ID="Total" runat="server" CssClass="style1">Total</asp:Label

</strong

</div

</form

</body

</html

Checkout.aspx.cs

using System;

using System.Collections.Generic;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class Checkout : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

Total.Text = Session["Total"].ToString();

Session.Remove("Total");

}

}

That's it , build and run the application
Have fun