Build a Shopping Cart in ASP.NET

Shopping carts are very important and can many times be the most intimidating part of building an e-commerce site. This tutorial will show how easy it can be to implement a shopping cart using ASP.NET. Additionally, several basic explanations will be provided to help beginning ASP.NET programmers understand this wonderful framework.



Quick Overview of ASP.NET

Since ASP.NET hasn't been covered too much on NETTUTS, I thought it would be good to include a brief overview of some of the things that distinguish it from other languages.
- Code is compiled. The first time an ASP.NET page is requested over the web, the code is compiled into one or more DLL files on the server. This gives you the ability to just copy code out to the server and it gives you the speed benefit of compiled code.
- ASP.NET is an object oriented framework. Every function, property and page is part of a class. For example, each web page is its own class that extends the Page class. The Page class has an event that is fired when the webpage is loaded called the "Page Load Event". You can write a function that subscribes to that event and is called on. The same principle applies to other events like the button click and "drop-down" "selected index changed" events.
- The logic is separate from the design and content. They interact with each other, but they are in separate places. Generally, this allows a designer to design without worrying about function and it allows the programmer to focus on function without looking at the design. You have the choice of putting them both in the same file or in different files. This is similar to model-view-controller model.



If you are new to ASP.NET (and you have Windows), you can try it out for free You can download Visual Studio Express by visiting the ASP.NET website. Also, when you create a website locally on your machine, you can run the website at any time and Visual Studio will quickly start a server on your computer and pull up your website in your default browser.
Step 1: Create the ShoppingCart Class
We need a place to store the items in the shopping cart as well as functions to manipulate the items. We'll create a ShoppingCart class for this. This class will also manage session storage.
First, we have to create the App_Code folder. To do this, go to the "Website" menu, then "Add ASP.NET Folder", and choose "App_Code." This is where we'll put all of our custom classes. These classes will automatically be accessible from the code in any of our pages (we don't need to reference it using something similar to "include" or anything). Then we can add a class to that folder by right-clicking on the folder and choosing "Add New Item."
Quick Tip: Regions in ASP.NET are really nice to organize and group code together. The nicest thing about them is that you can open and close regions to minimize the amount of code that you are looking at or quickly find your way around a file.

1 |
|
2 |
using System.Collections.Generic; |
3 |
using System.Web; |
4 |
|
5 |
/**
|
6 |
* The ShoppingCart class
|
7 |
*
|
8 |
* Holds the items that are in the cart and provides methods for their manipulation
|
9 |
*/
|
10 |
public class ShoppingCart { |
11 |
#region Properties |
12 |
|
13 |
public List<CartItem> Items { get; private set; } |
14 |
|
15 |
#endregion |
16 |
|
17 |
#region Singleton Implementation |
18 |
|
19 |
|
20 |
|
21 |
// Readonly properties can only be set in initialization or in a constructor
|
22 |
public static readonly ShoppingCart Instance; |
23 |
|
24 |
// The static constructor is called as soon as the class is loaded into memory
|
25 |
static ShoppingCart() { |
26 |
// If the cart is not in the session, create one and put it there
|
27 |
// Otherwise, get it from the session
|
28 |
if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) { |
29 |
Instance = new ShoppingCart(); |
30 |
Instance.Items = new List<CartItem>(); |
31 |
HttpContext.Current.Session["ASPNETShoppingCart"] = Instance; |
32 |
} else { |
33 |
Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"]; |
34 |
}
|
35 |
}
|
36 |
|
37 |
// A protected constructor ensures that an object can't be created from outside
|
38 |
protected ShoppingCart() { } |
39 |
|
40 |
#endregion |
41 |
|
42 |
#region Item Modification Methods |
43 |
/**
|
44 |
* AddItem() - Adds an item to the shopping
|
45 |
*/
|
46 |
public void AddItem(int productId) { |
47 |
// Create a new item to add to the cart
|
48 |
CartItem newItem = new CartItem(productId); |
49 |
|
50 |
// If this item already exists in our list of items, increase the quantity
|
51 |
// Otherwise, add the new item to the list
|
52 |
if (Items.Contains(newItem)) { |
53 |
foreach (CartItem item in Items) { |
54 |
if (item.Equals(newItem)) { |
55 |
item.Quantity++; |
56 |
return; |
57 |
}
|
58 |
}
|
59 |
} else { |
60 |
newItem.Quantity = 1; |
61 |
Items.Add(newItem); |
62 |
}
|
63 |
}
|
64 |
|
65 |
/**
|
66 |
* SetItemQuantity() - Changes the quantity of an item in the cart
|
67 |
*/
|
68 |
public void SetItemQuantity(int productId, int quantity) { |
69 |
// If we are setting the quantity to 0, remove the item entirely
|
70 |
if (quantity == 0) { |
71 |
RemoveItem(productId); |
72 |
return; |
73 |
}
|
74 |
|
75 |
// Find the item and update the quantity
|
76 |
CartItem updatedItem = new CartItem(productId); |
77 |
|
78 |
foreach (CartItem item in Items) { |
79 |
if (item.Equals(updatedItem)) { |
80 |
item.Quantity = quantity; |
81 |
return; |
82 |
}
|
83 |
}
|
84 |
}
|
85 |
|
86 |
/**
|
87 |
* RemoveItem() - Removes an item from the shopping cart
|
88 |
*/
|
89 |
public void RemoveItem(int productId) { |
90 |
CartItem removedItem = new CartItem(productId); |
91 |
Items.Remove(removedItem); |
92 |
}
|
93 |
#endregion |
94 |
|
95 |
#region Reporting Methods |
96 |
/**
|
97 |
* GetSubTotal() - returns the total price of all of the items
|
98 |
* before tax, shipping, etc.
|
99 |
*/
|
100 |
public decimal GetSubTotal() { |
101 |
decimal subTotal = 0; |
102 |
foreach (CartItem item in Items) |
103 |
subTotal += item.TotalPrice; |
104 |
|
105 |
return subTotal; |
106 |
}
|
107 |
#endregion |
108 |
}
|
Step 2: The CartItem & Product Classes
With a place to store our shopping cart items, we need to be able to store information about each item. We'll create a CartItem class that will do this. We'll also create a simple Product class that will simulate a way to grab data about the products we're selling.
The CartItem class:
1 |
|
2 |
using System; |
3 |
|
4 |
/**
|
5 |
* The CartItem Class
|
6 |
*
|
7 |
* Basically a structure for holding item data
|
8 |
*/
|
9 |
public class CartItem : IEquatable<CartItem> { |
10 |
#region Properties |
11 |
|
12 |
// A place to store the quantity in the cart
|
13 |
// This property has an implicit getter and setter.
|
14 |
public int Quantity { get; set; } |
15 |
|
16 |
private int _productId; |
17 |
public int ProductId { |
18 |
get { return _productId; } |
19 |
set { |
20 |
// To ensure that the Prod object will be re-created
|
21 |
_product = null; |
22 |
_productId = value; |
23 |
}
|
24 |
}
|
25 |
|
26 |
private Product _product = null; |
27 |
public Product Prod { |
28 |
get { |
29 |
// Lazy initialization - the object won't be created until it is needed
|
30 |
if (_product == null) { |
31 |
_product = new Product(ProductId); |
32 |
}
|
33 |
return _product; |
34 |
}
|
35 |
}
|
36 |
|
37 |
public string Description { |
38 |
get { return Prod.Description; } |
39 |
}
|
40 |
|
41 |
public decimal UnitPrice { |
42 |
get { return Prod.Price; } |
43 |
}
|
44 |
|
45 |
public decimal TotalPrice { |
46 |
get { return UnitPrice * Quantity; } |
47 |
}
|
48 |
|
49 |
#endregion |
50 |
|
51 |
// CartItem constructor just needs a productId
|
52 |
public CartItem(int productId) { |
53 |
this.ProductId = productId; |
54 |
}
|
55 |
|
56 |
/**
|
57 |
* Equals() - Needed to implement the IEquatable interface
|
58 |
* Tests whether or not this item is equal to the parameter
|
59 |
* This method is called by the Contains() method in the List class
|
60 |
* We used this Contains() method in the ShoppingCart AddItem() method
|
61 |
*/
|
62 |
public bool Equals(CartItem item) { |
63 |
return item.ProductId == this.ProductId; |
64 |
}
|
65 |
}
|
The Product class:
1 |
|
2 |
/**
|
3 |
* The Product class
|
4 |
*
|
5 |
* This is just to simulate some way of accessing data about our products
|
6 |
*/
|
7 |
public class Product |
8 |
{
|
9 |
|
10 |
public int Id { get; set; } |
11 |
public decimal Price { get; set; } |
12 |
public string Description { get; set; } |
13 |
|
14 |
public Product(int id) |
15 |
{
|
16 |
this.Id = id; |
17 |
switch (id) { |
18 |
case 1: |
19 |
this.Price = 19.95m; |
20 |
this.Description = "Shoes"; |
21 |
break; |
22 |
case 2: |
23 |
this.Price = 9.95m; |
24 |
this.Description = "Shirt"; |
25 |
break; |
26 |
case 3: |
27 |
this.Price = 14.95m; |
28 |
this.Description = "Pants"; |
29 |
break; |
30 |
}
|
31 |
}
|
32 |
|
33 |
}
|
Definition: A "property" in ASP.NET is a variable in a class that has a setter, a getter, or both. This is similar to other languages, but in ASP.NET, the word property refers specifically to this. An example of this is the ProductId property in the CartItem class. It is not simply a variable in a class with a method to get or set it. It is declared in a special way with get{} and set{} blocks.
Let's Add Items to the Cart
After having our heads in the code for so long, it's time we do something visual. This page will simply be a way to add items to the cart. All we need is a few items with "Add to Cart" links. Let's put this code in the Default.aspx page.
1 |
|
2 |
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> |
3 |
|
4 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
5 |
|
6 |
<html xmlns="http://www.w3.org/1999/xhtml"> |
7 |
<head runat="server"> |
8 |
<title>My Store</title> |
9 |
<link href="Styles/StyleSheet.css" rel="stylesheet" type="text/css" /> |
10 |
</head>
|
11 |
<body>
|
12 |
|
13 |
<form id="form1" runat="server"> |
14 |
|
15 |
<div class="container"> |
16 |
<h1>My Store</h1> |
17 |
|
18 |
<div class="products"> |
19 |
<div>Shoes - <asp:LinkButton runat="server" ID="btnAddShirt" OnClick="btnAddShoes_Click">Add To Cart</asp:LinkButton></div> |
20 |
|
21 |
<div>Shirt - <asp:LinkButton runat="server" ID="btnAddShorts" OnClick="btnAddShirt_Click">Add To Cart</asp:LinkButton></div> |
22 |
<div>Pants - <asp:LinkButton runat="server" ID="btnAddShoes" OnClick="btnAddPants_Click">Add To Cart</asp:LinkButton></div> |
23 |
</div>
|
24 |
|
25 |
|
26 |
<a href="ViewCart.aspx">View Cart</a> |
27 |
</div>
|
28 |
|
29 |
</form>
|
30 |
</body>
|
31 |
</html>
|
As you can see, the only thing happening here is that we have a few LinkButtons that have OnClick event handlers associated to them.
In the code-behind page, we have 4 event handlers. We have one for each LinkButton that just adds an item to the shopping cart and redirects the user to view their cart. We also have a Page_Load event handler which is created by the IDE by default that we didn't need to use.
1 |
|
2 |
using System; |
3 |
|
4 |
public partial class _Default : System.Web.UI.Page { |
5 |
protected void Page_Load(object sender, EventArgs e) { |
6 |
|
7 |
}
|
8 |
|
9 |
protected void btnAddShoes_Click(object sender, EventArgs e) { |
10 |
// Add product 1 to the shopping cart
|
11 |
ShoppingCart.Instance.AddItem(1); |
12 |
|
13 |
// Redirect the user to view their shopping cart
|
14 |
Response.Redirect("ViewCart.aspx"); |
15 |
}
|
16 |
|
17 |
protected void btnAddShirt_Click(object sender, EventArgs e) { |
18 |
ShoppingCart.Instance.AddItem(2); |
19 |
Response.Redirect("ViewCart.aspx"); |
20 |
}
|
21 |
|
22 |
protected void btnAddPants_Click(object sender, EventArgs e) { |
23 |
ShoppingCart.Instance.AddItem(3); |
24 |
Response.Redirect("ViewCart.aspx"); |
25 |
}
|
26 |
|
27 |
}
|
Build the Shopping Cart Page



Finally, what we've been preparing for the whole time—the shopping cart! Let's just look at ViewCart.aspx first and I'll explain it after that.
1 |
|
2 |
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ViewCart.aspx.cs" Inherits="ViewCart" %> |
3 |
|
4 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
5 |
|
6 |
<html xmlns="http://www.w3.org/1999/xhtml"> |
7 |
<head runat="server"> |
8 |
<title>Shopping Cart</title> |
9 |
<link href="Styles/StyleSheet.css" rel="stylesheet" type="text/css" /> |
10 |
</head>
|
11 |
<body>
|
12 |
|
13 |
<form id="form1" runat="server"> |
14 |
<div class="container"> |
15 |
<h1>Shopping Cart</h1> |
16 |
<a href="Default.aspx">< Back to Products</a> |
17 |
|
18 |
<br /><br /> |
19 |
<asp:GridView runat="server" ID="gvShoppingCart" AutoGenerateColumns="false" EmptyDataText="There is nothing in your shopping cart." GridLines="None" Width="100%" CellPadding="5" ShowFooter="true" DataKeyNames="ProductId" OnRowDataBound="gvShoppingCart_RowDataBound" OnRowCommand="gvShoppingCart_RowCommand"> |
20 |
<HeaderStyle HorizontalAlign="Left" BackColor="#3D7169" ForeColor="#FFFFFF" /> |
21 |
<FooterStyle HorizontalAlign="Right" BackColor="#6C6B66" ForeColor="#FFFFFF" /> |
22 |
<AlternatingRowStyle BackColor="#F8F8F8" /> |
23 |
<Columns>
|
24 |
|
25 |
<asp:BoundField DataField="Description" HeaderText="Description" /> |
26 |
<asp:TemplateField HeaderText="Quantity"> |
27 |
<ItemTemplate>
|
28 |
<asp:TextBox runat="server" ID="txtQuantity" Columns="5" Text='<%# Eval("Quantity") %>'></asp:TextBox><br /> |
29 |
<asp:LinkButton runat="server" ID="btnRemove" Text="Remove" CommandName="Remove" CommandArgument='<%# Eval("ProductId") %>' style="font-size:12px;"></asp:LinkButton> |
30 |
|
31 |
</ItemTemplate>
|
32 |
</asp:TemplateField>
|
33 |
<asp:BoundField DataField="UnitPrice" HeaderText="Price" ItemStyle-HorizontalAlign="Right" HeaderStyle-HorizontalAlign="Right" DataFormatString="{0:C}" /> |
34 |
<asp:BoundField DataField="TotalPrice" HeaderText="Total" ItemStyle-HorizontalAlign="Right" HeaderStyle-HorizontalAlign="Right" DataFormatString="{0:C}" /> |
35 |
</Columns>
|
36 |
</asp:GridView>
|
37 |
|
38 |
<br /> |
39 |
<asp:Button runat="server" ID="btnUpdateCart" Text="Update Cart" OnClick="btnUpdateCart_Click" /> |
40 |
</div>
|
41 |
</form>
|
42 |
</body>
|
43 |
</html>
|
The GridView control is a powerful control that can seem complicated at first. I won't discuss the style elements because they are self-explanatory. (There are some principles here that I'm not going to explain in depth. I am just going to try to get the main idea across). Let's break it down.
-
Giving the GridView an ID will allow us to access the GridView from the code-behind using that ID.
1
ID="gvShoppingCart"
-
The GridView will automatically generate columns and column names from the data that we supply unless we specifically tell it not to.
1
AutoGenerateColumns="false"
-
We can tell the GridView what to display in case we supply it with no data.
1
EmptyDataText="There is nothing in your shopping cart."
-
We want to show the footer so that we can display the total price.
1
ShowFooter="true"
-
It will be nice for us to have an array of ProductIds indexed by the row index when we are updating the quantity of a cart item in the code-behind. This will do that for us:
1
DataKeyNames="ProductId"
-
We need events to respond to two events: RowDataBound and RowCommand. Basically, RowDataBound is fired when the GridView takes a row of our data and adds it to the table. We are only using this event to respond to the footer being bound so that we can customize what we want displayed there. RowCommand is fired when a link or a button is clicked from inside the GridView. In this case, it is the "Remove" link.
1
OnRowDataBound="gvShoppingCart_RowDataBound" OnRowCommand="gvShoppingCart_RowCommand"
Now let's talk about the columns. We define the columns here and the GridView will take every row in the data that we supply and map the data in that row to the column that it should display in. The simplest column is the BoundField. In our case, it is going to look for a "Description" property in our CartItem object and display it in the first column. The header for that column will also display "Description."
We needed the quantity to display inside a textbox rather than just displaying as text, so we used a TemplateField. The TemplateField allows you to put whatever you want in that column. If you need some data from the row, you just insert <%# Eval("PropertyName") %>. The LinkButton that we put in our TemplateField has a CommandName and a CommandArgument, both of which will be passed to our GridView's RowCommand event handler.
The last thing worth mentioning here is that the last two BoundFields have a DataFormatString specified. This is just one of the many format strings that ASP.NET provides. This one formats the number as a currency. See the Microsoft documentation for other format strings.
Now we can look at the code-behind page. I have supplied lots of comments here to describe what is happening.
The End Result:
Now we have a nice working shopping cart!



You Also Might Like...

How to Search a Website Using ASP.NET 3.5 - screencast
Oct 1st in Screencasts by Jeffrey Way
I’m happy to say that today, we are posting our very first article on ASP.NET. In this screencast, I’ll show you how to implement a simple search functionality into your personal website. We’ll go over many of the new features in ASP.NET 3.5, such as LINQ and many of the AJAX controls that ship with Visual Studio/Web Developer.
- Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
56