Shopping Cart
by Erik Reitan
Download Wingtip Toys Sample Project (C#) or Download E-book (PDF)
This tutorial series will teach you the basics of building an ASP.NET Web Forms application using ASP.NET 4.5 and Microsoft Visual Studio Express 2013 for Web. A Visual Studio 2013 project with C# source code is available to accompany this tutorial series.
This tutorial describes the business logic required to add a shopping cart to the Wingtip Toys sample ASP.NET Web Forms application. This tutorial builds on the previous tutorial “Display Data Items and Details” and is part of the Wingtip Toy Store tutorial series. When you’ve completed this tutorial, the users of your sample app will be able to add, remove, and modify the products in their shopping cart.
What you’ll learn:
- How to create a shopping cart for the web application.
- How to enable users to add items to the shopping cart.
- How to add a GridView control to display shopping cart details.
- How to calculate and display the order total.
- How to remove and update items in the shopping cart.
- How to include a shopping cart counter.
Code features in this tutorial:
- Entity Framework Code First
- Data Annotations
- Strongly typed data controls
- Model binding
Creating a Shopping Cart
Earlier in this tutorial series, you added pages and code to view product data from a database. In this tutorial, you’ll create a shopping cart to manage the products that users are interested in buying. Users will be able to browse and add items to the shopping cart even if they are not registered or logged in. To manage shopping cart access, you will assign users a unique ID
using a globally unique identifier (GUID) when the user accesses the shopping cart for the first time. You’ll store this ID
using the ASP.NET Session state.
[!NOTE]
The ASP.NET Session state is a convenient place to store user-specific information which will expire after the user leaves the site. While misuse of session state can have performance implications on larger sites, light use of session state works well for demonstration purposes. The Wingtip Toys sample project shows how to use session state without an external provider, where session state is stored in-process on the web server hosting the site. For larger sites that provide multiple instances of an application or for sites that run multiple instances of an application on different servers, consider using Windows Azure Cache Service. This Cache Service provides a distributed caching service that is external to the web site and solves the problem of using in-process session state. For more information see, How to Use ASP.NET Session State with Windows Azure Web Sites.
Add CartItem as a Model Class
Earlier in this tutorial series, you defined the schema for the category and product data by creating the Category
and Product
classes in the Models folder. Now, add a new class to define the schema for the shopping cart. Later in this tutorial, you will add a class to handle data access to the CartItem
table. This class will provide the business logic to add, remove, and update items in the shopping cart.
Right-click the Models folder and select Add -> New Item.
The Add New Item dialog box is displayed. Select Code, and then select Class.
- Name this new class CartItem.cs.
- Click Add.
The new class file is displayed in the editor. Replace the default code with the following code:
[!code-csharpMain]
1: using System.ComponentModel.DataAnnotations;
2:
3: namespace WingtipToys.Models
4: {
5: public class CartItem
6: {
7: [Key]
8: public string ItemId { get; set; }
9:
10: public string CartId { get; set; }
11:
12: public int Quantity { get; set; }
13:
14: public System.DateTime DateCreated { get; set; }
15:
16: public int ProductId { get; set; }
17:
18: public virtual Product Product { get; set; }
19:
20: }
21: }
The CartItem
class contains the schema that will define each product a user adds to the shopping cart. This class is similar to the other schema classes you created earlier in this tutorial series. By convention, Entity Framework Code First expects that the primary key for the CartItem
table will be either CartItemId
or ID
. However, the code overrides the default behavior by using the data annotation [Key]
attribute. The Key
attribute of the ItemId property specifies that the ItemID
property is the primary key.
The CartId
property specifies the ID
of the user that is associated with the item to purchase. You’ll add code to create this user ID
when the user accesses the shopping cart. This ID
will also be stored as an ASP.NET Session variable.
Update the Product Context
In addition to adding the CartItem
class, you will need to update the database context class that manages the entity classes and that provides data access to the database. To do this, you will add the newly created CartItem
model class to the ProductContext
class.
- In Solution Explorer, find and open the ProductContext.cs file in the Models folder.
Add the highlighted code to the ProductContext.cs file as follows:
[!code-csharpMain]
1: using System.Data.Entity;
2:
3: namespace WingtipToys.Models
4: {
5: public class ProductContext : DbContext
6: {
7: public ProductContext()
8: : base("WingtipToys")
9: {
10: }
11:
12: public DbSet<Category> Categories { get; set; }
13: public DbSet<Product> Products { get; set; }
14: public DbSet<CartItem> ShoppingCartItems { get; set; }
15: }
16: }
As mentioned previously in this tutorial series, the code in the ProductContext.cs file adds the System.Data.Entity
namespace so that you have access to all the core functionality of the Entity Framework. This functionality includes the capability to query, insert, update, and delete data by working with strongly typed objects. The ProductContext
class adds access to the newly added CartItem
model class.
Managing the Shopping Cart Business Logic
Next, you’ll create the ShoppingCart
class in a new Logic folder. The ShoppingCart
class handles data access to the CartItem
table. The class will also include the business logic to add, remove, and update items in the shopping cart.
The shopping cart logic that you will add will contain the functionality to manage the following actions:
- Adding items to the shopping cart
- Removing items from the shopping cart
- Getting the shopping cart ID
- Retrieving items from the shopping cart
- Totaling the amount of all the shopping cart items
- Updating the shopping cart data
A shopping cart page (ShoppingCart.aspx) and the shopping cart class will be used together to access shopping cart data. The shopping cart page will display all the items the user adds to the shopping cart. Besides the shopping cart page and class, you’ll create a page (AddToCart.aspx) to add products to the shopping cart. You will also add code to the ProductList.aspx page and the ProductDetails.aspx page that will provide a link to the AddToCart.aspx page, so that the user can add products to the shopping cart.
The following diagram shows the basic process that occurs when the user adds a product to the shopping cart.
When the user clicks the Add To Cart link on either the ProductList.aspx page or the ProductDetails.aspx page, the application will navigate to the AddToCart.aspx page and then automatically to the ShoppingCart.aspx page. The AddToCart.aspx page will add the select product to the shopping cart by calling a method in the ShoppingCart class. The ShoppingCart.aspx page will display the products that have been added to the shopping cart.
Creating the Shopping Cart Class
The ShoppingCart
class will be added to a separate folder in the application so that there will be a clear distinction between the model (Models folder), the pages (root folder) and the logic (Logic folder).
- In Solution Explorer, right-click the WingtipToysproject and select Add->New Folder. Name the new folder Logic.
- Right-click the Logic folder and then select Add -> New Item.
- Add a new class file named ShoppingCartActions.cs.
Replace the default code with the following code:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using WingtipToys.Models;
6:
7: namespace WingtipToys.Logic
8: {
9: public class ShoppingCartActions : IDisposable
10: {
11: public string ShoppingCartId { get; set; }
12:
13: private ProductContext _db = new ProductContext();
14:
15: public const string CartSessionKey = "CartId";
16:
17: public void AddToCart(int id)
18: {
19: // Retrieve the product from the database.
20: ShoppingCartId = GetCartId();
21:
22: var cartItem = _db.ShoppingCartItems.SingleOrDefault(
23: c => c.CartId == ShoppingCartId
24: && c.ProductId == id);
25: if (cartItem == null)
26: {
27: // Create a new cart item if no cart item exists.
28: cartItem = new CartItem
29: {
30: ItemId = Guid.NewGuid().ToString(),
31: ProductId = id,
32: CartId = ShoppingCartId,
33: Product = _db.Products.SingleOrDefault(
34: p => p.ProductID == id),
35: Quantity = 1,
36: DateCreated = DateTime.Now
37: };
38:
39: _db.ShoppingCartItems.Add(cartItem);
40: }
41: else
42: {
43: // If the item does exist in the cart,
44: // then add one to the quantity.
45: cartItem.Quantity++;
46: }
47: _db.SaveChanges();
48: }
49:
50: public void Dispose()
51: {
52: if (_db != null)
53: {
54: _db.Dispose();
55: _db = null;
56: }
57: }
58:
59: public string GetCartId()
60: {
61: if (HttpContext.Current.Session[CartSessionKey] == null)
62: {
63: if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
64: {
65: HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
66: }
67: else
68: {
69: // Generate a new random GUID using System.Guid class.
70: Guid tempCartId = Guid.NewGuid();
71: HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
72: }
73: }
74: return HttpContext.Current.Session[CartSessionKey].ToString();
75: }
76:
77: public List<CartItem> GetCartItems()
78: {
79: ShoppingCartId = GetCartId();
80:
81: return _db.ShoppingCartItems.Where(
82: c => c.CartId == ShoppingCartId).ToList();
83: }
84: }
85: }
The AddToCart
method enables individual products to be included in the shopping cart based on the product ID
. The product is added to the cart, or if the cart already contains an item for that product, the quantity is incremented.
The GetCartId
method returns the cart ID
for the user. The cart ID
is used to track the items that a user has in their shopping cart. If the user does not have an existing cart ID
, a new cart ID
is created for them. If the user is signed in as a registered user, the cart ID
is set to their user name. However, if the user is not signed in, the cart ID
is set to a unique value (a GUID). A GUID ensures that only one cart is created for each user, based on session.
The GetCartItems
method returns a list of shopping cart items for the user. Later in this tutorial, you will see that model binding is used to display the cart items in the shopping cart using the GetCartItems
method.
Creating the Add-To-Cart Functionality
As mentioned earlier, you will create a processing page named AddToCart.aspx that will be used to add new products to the shopping cart of the user. This page will call the AddToCart
method in the ShoppingCart
class that you just created. The AddToCart.aspx page will expect that a product ID
is passed to it. This product ID
will be used when calling the AddToCart
method in the ShoppingCart
class.
[!NOTE]
You will be modifying the code-behind (AddToCart.aspx.cs) for this page, not the page UI (AddToCart.aspx).
To create the Add-To-Cart functionality:
- In Solution Explorer, right-click the WingtipToysproject, click Add -> New Item.
The Add New Item dialog box is displayed. Add a standard new page (Web Form) to the application named AddToCart.aspx.
- In Solution Explorer, right-click the AddToCart.aspx page and then click View Code. The AddToCart.aspx.cs code-behind file is opened in the editor.
Replace the existing code in the AddToCart.aspx.cs code-behind with the following:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7: using System.Diagnostics;
8: using WingtipToys.Logic;
9:
10: namespace WingtipToys
11: {
12: public partial class AddToCart : System.Web.UI.Page
13: {
14: protected void Page_Load(object sender, EventArgs e)
15: {
16: string rawId = Request.QueryString["ProductID"];
17: int productId;
18: if (!String.IsNullOrEmpty(rawId) && int.TryParse(rawId, out productId))
19: {
20: using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
21: {
22: usersShoppingCart.AddToCart(Convert.ToInt16(rawId));
23: }
24:
25: }
26: else
27: {
28: Debug.Fail("ERROR : We should never get to AddToCart.aspx without a ProductId.");
29: throw new Exception("ERROR : It is illegal to load AddToCart.aspx without setting a ProductId.");
30: }
31: Response.Redirect("ShoppingCart.aspx");
32: }
33: }
34: }
When the AddToCart.aspx page is loaded, the product ID
is retrieved from the query string. Next, an instance of the shopping cart class is created and used to call the AddToCart
method that you added earlier in this tutorial. The AddToCart
method, contained in the ShoppingCartActions.cs file, includes the logic to add the selected product to the shopping cart or increment the product quantity of the selected product. If the product hasn’t been added to the shopping cart, the product is added to the CartItem
table of the database. If the product has already been added to the shopping cart and the user adds an additional item of the same product, the product quantity is incremented in the CartItem
table. Finally, the page redirects back to the ShoppingCart.aspx page that you’ll add in the next step, where the user sees an updated list of items in the cart.
As previously mentioned, a user ID
is used to identify the products that are associated with a specific user. This ID
is added to a row in the CartItem
table each time the user adds a product to the shopping cart.
Creating the Shopping Cart UI
The ShoppingCart.aspx page will display the products that the user has added to their shopping cart. It will also provide the ability to add, remove and update items in the shopping cart.
- In Solution Explorer, right-click WingtipToys, click Add -> New Item.
The Add New Item dialog box is displayed. - Add a new page (Web Form) that includes a master page by selecting Web Form using Master Page. Name the new page ShoppingCart.aspx.
- Select Site.Master to attach the master page to the newly created .aspx page.
In the ShoppingCart.aspx page, replace the existing markup with the following markup:
[!code-aspxMain]
1: <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ShoppingCart.aspx.cs" Inherits="WingtipToys.ShoppingCart" %>
2: <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
3: <div id="ShoppingCartTitle" runat="server" class="ContentHead"><h1>Shopping Cart</h1></div>
4: <asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
5: ItemType="WingtipToys.Models.CartItem" SelectMethod="GetShoppingCartItems"
6: CssClass="table table-striped table-bordered" >
7: <Columns>
8: <asp:BoundField DataField="ProductID" HeaderText="ID" SortExpression="ProductID" />
9: <asp:BoundField DataField="Product.ProductName" HeaderText="Name" />
10: <asp:BoundField DataField="Product.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}"/>
11: <asp:TemplateField HeaderText="Quantity">
12: <ItemTemplate>
13: <asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.Quantity %>"></asp:TextBox>
14: </ItemTemplate>
15: </asp:TemplateField>
16: <asp:TemplateField HeaderText="Item Total">
17: <ItemTemplate>
18: <%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) * Convert.ToDouble(Item.Product.UnitPrice)))%>
19: </ItemTemplate>
20: </asp:TemplateField>
21: <asp:TemplateField HeaderText="Remove Item">
22: <ItemTemplate>
23: <asp:CheckBox id="Remove" runat="server"></asp:CheckBox>
24: </ItemTemplate>
25: </asp:TemplateField>
26: </Columns>
27: </asp:GridView>
28: <div>
29: <p></p>
30: <strong>
31: <asp:Label ID="LabelTotalText" runat="server" Text="Order Total: "></asp:Label>
32: <asp:Label ID="lblTotal" runat="server" EnableViewState="false"></asp:Label>
33: </strong>
34: </div>
35: <br />
36: </asp:Content>
The ShoppingCart.aspx page includes a GridView control named CartList
. This control uses model binding to bind the shopping cart data from the database to the GridView control. When you set the ItemType
property of the GridView control, the data-binding expression Item
is available in the markup of the control and the control becomes strongly typed. As mentioned earlier in this tutorial series, you can select details of the Item
object using IntelliSense. To configure a data control to use model binding to select data, you set the SelectMethod
property of the control. In the markup above, you set the SelectMethod
to use the GetShoppingCartItems method which returns a list of CartItem
objects. The GridView data control calls the method at the appropriate time in the page life cycle and automatically binds the returned data. The GetShoppingCartItems
method must still be added.
Retrieving the Shopping Cart Items
Next, you add code to the ShoppingCart.aspx.cs code-behind to retrieve and populate the Shopping Cart UI.
- In Solution Explorer, right-click the ShoppingCart.aspx page and then click View Code. The ShoppingCart.aspx.cs code-behind file is opened in the editor.
Replace the existing code with the following:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7: using WingtipToys.Models;
8: using WingtipToys.Logic;
9:
10: namespace WingtipToys
11: {
12: public partial class ShoppingCart : System.Web.UI.Page
13: {
14: protected void Page_Load(object sender, EventArgs e)
15: {
16:
17: }
18:
19: public List<CartItem> GetShoppingCartItems()
20: {
21: ShoppingCartActions actions = new ShoppingCartActions();
22: return actions.GetCartItems();
23: }
24: }
25: }
As mentioned above, the GridView
data control calls the GetShoppingCartItems
method at the appropriate time in the page life cycle and automatically binds the returned data. The GetShoppingCartItems
method creates an instance of the ShoppingCartActions
object. Then, the code uses that instance to return the items in the cart by calling the GetCartItems
method.
Adding Products to the Shopping Cart
When either the ProductList.aspx or the ProductDetails.aspx page is displayed, the user will be able to add the product to the shopping cart using a link. When they click the link, the application navigates to the processing page named AddToCart.aspx. The AddToCart.aspx page will call the AddToCart
method in the ShoppingCart
class that you added earlier in this tutorial.
Now, you’ll add an Add to Cart link to both the ProductList.aspx page and the ProductDetails.aspx page. This link will include the product ID
that is retrieved from the database.
- In Solution Explorer, find and open the page named ProductList.aspx.
Add the markup highlighted in yellow to the ProductList.aspx page so that the entire page appears as follows:
[!code-aspxMain]
1: <%@ Page Title="Products" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
2: CodeBehind="ProductList.aspx.cs" Inherits="WingtipToys.ProductList" %>
3: <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
4: <section>
5: <div>
6: <hgroup>
7: <h2><%: Page.Title %></h2>
8: </hgroup>
9:
10: <asp:ListView ID="productList" runat="server"
11: DataKeyNames="ProductID" GroupItemCount="4"
12: ItemType="WingtipToys.Models.Product" SelectMethod="GetProducts">
13: <EmptyDataTemplate>
14: <table runat="server">
15: <tr>
16: <td>No data was returned.</td>
17: </tr>
18: </table>
19: </EmptyDataTemplate>
20: <EmptyItemTemplate>
21: <td runat="server" />
22: </EmptyItemTemplate>
23: <GroupTemplate>
24: <tr id="itemPlaceholderContainer" runat="server">
25: <td id="itemPlaceholder" runat="server"></td>
26: </tr>
27: </GroupTemplate>
28: <ItemTemplate>
29: <td runat="server">
30: <table>
31: <tr>
32: <td>
33: <a href="ProductDetails.aspx?productID=<%#:Item.ProductID%>">
34: <img src="/Catalog/Images/Thumbs/<%#:Item.ImagePath%>"
35: width="100" height="75" style="border: solid" /></a>
36: </td>
37: </tr>
38: <tr>
39: <td>
40: <a href="ProductDetails.aspx?productID=<%#:Item.ProductID%>">
41: <span>
42: <%#:Item.ProductName%>
43: </span>
44: </a>
45: <br />
46: <span>
47: <b>Price: </b><%#:String.Format("{0:c}", Item.UnitPrice)%>
48: </span>
49: <br />
50: <a href="/AddToCart.aspx?productID=<%#:Item.ProductID %>">
51: <span class="ProductListItem">
52: <b>Add To Cart<b>
53: </span>
54: </a>
55: </td>
56: </tr>
57: <tr>
58: <td> </td>
59: </tr>
60: </table>
61: </p>
62: </td>
63: </ItemTemplate>
64: <LayoutTemplate>
65: <table runat="server" style="width:100%;">
66: <tbody>
67: <tr runat="server">
68: <td runat="server">
69: <table id="groupPlaceholderContainer" runat="server" style="width:100%">
70: <tr id="groupPlaceholder" runat="server"></tr>
71: </table>
72: </td>
73: </tr>
74: <tr runat="server">
75: <td runat="server"></td>
76: </tr>
77: <tr></tr>
78: </tbody>
79: </table>
80: </LayoutTemplate>
81: </asp:ListView>
82: </div>
83: </section>
84: </asp:Content>
Testing the Shopping Cart
Run the application to see how you add products to the shopping cart.
- Press F5 to run the application.
After the project recreates the database, the browser will open and show the Default.aspx page. Select Cars from the category navigation menu.
The ProductList.aspx page is displayed showing only products included in the “Cars” category.Click the Add to Cart link next to the first product listed (the convertible car).
The ShoppingCart.aspx page is displayed, showing the selection in your shopping cart.- View additional products by selecting Planes from the category navigation menu.
- Click the Add to Cart link next to the first product listed.
The ShoppingCart.aspx page is displayed with the additional item. Close the browser.
Calculating and Displaying the Order Total
In addition to adding products to the shopping cart, you will add a GetTotal
method to the ShoppingCart
class and display the total order amount in the shopping cart page.
- In Solution Explorer, open the ShoppingCartActions.cs file in the Logic folder.
Add the following
GetTotal
method highlighted in yellow to theShoppingCart
class, so that the class appears as follows:[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using WingtipToys.Models;
6:
7: namespace WingtipToys.Logic
8: {
9: public class ShoppingCartActions : IDisposable
10: {
11: public string ShoppingCartId { get; set; }
12:
13: private ProductContext _db = new ProductContext();
14:
15: public const string CartSessionKey = "CartId";
16:
17: public void AddToCart(int id)
18: {
19: // Retrieve the product from the database.
20: ShoppingCartId = GetCartId();
21:
22: var cartItem = _db.ShoppingCartItems.SingleOrDefault(
23: c => c.CartId == ShoppingCartId
24: && c.ProductId == id);
25: if (cartItem == null)
26: {
27: // Create a new cart item if no cart item exists.
28: cartItem = new CartItem
29: {
30: ItemId = Guid.NewGuid().ToString(),
31: ProductId = id,
32: CartId = ShoppingCartId,
33: Product = _db.Products.SingleOrDefault(
34: p => p.ProductID == id),
35: Quantity = 1,
36: DateCreated = DateTime.Now
37: };
38:
39: _db.ShoppingCartItems.Add(cartItem);
40: }
41: else
42: {
43: // If the item does exist in the cart,
44: // then add one to the quantity.
45: cartItem.Quantity++;
46: }
47: _db.SaveChanges();
48: }
49:
50: public void Dispose()
51: {
52: if (_db != null)
53: {
54: _db.Dispose();
55: _db = null;
56: }
57: }
58:
59: public string GetCartId()
60: {
61: if (HttpContext.Current.Session[CartSessionKey] == null)
62: {
63: if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
64: {
65: HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
66: }
67: else
68: {
69: // Generate a new random GUID using System.Guid class.
70: Guid tempCartId = Guid.NewGuid();
71: HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
72: }
73: }
74: return HttpContext.Current.Session[CartSessionKey].ToString();
75: }
76:
77: public List<CartItem> GetCartItems()
78: {
79: ShoppingCartId = GetCartId();
80:
81: return _db.ShoppingCartItems.Where(
82: c => c.CartId == ShoppingCartId).ToList();
83: }
84:
85: public decimal GetTotal()
86: {
87: ShoppingCartId = GetCartId();
88: // Multiply product price by quantity of that product to get
89: // the current price for each of those products in the cart.
90: // Sum all product price totals to get the cart total.
91: decimal? total = decimal.Zero;
92: total = (decimal?)(from cartItems in _db.ShoppingCartItems
93: where cartItems.CartId == ShoppingCartId
94: select (int?)cartItems.Quantity *
95: cartItems.Product.UnitPrice).Sum();
96: return total ?? decimal.Zero;
97: }
98: }
99: }
First, the GetTotal
method gets the ID of the shopping cart for the user. Then the method gets the cart total by multiplying the product price by the product quantity for each product listed in the cart.
[!NOTE]
The above code uses the nullable type “
int?
”. Nullable types can represent all the values of an underlying type, and also as a null value. For more information see, Using Nullable Types.
Modify the Shopping Cart Display
Next you’ll modify the code for the ShoppingCart.aspx page to call the GetTotal
method and display that total on the ShoppingCart.aspx page when the page loads.
- In Solution Explorer, right-click the ShoppingCart.aspx page and select View Code.
In the ShoppingCart.aspx.cs file, update the
Page_Load
handler by adding the following code highlighted in yellow:[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7: using WingtipToys.Models;
8: using WingtipToys.Logic;
9:
10: namespace WingtipToys
11: {
12: public partial class ShoppingCart : System.Web.UI.Page
13: {
14: protected void Page_Load(object sender, EventArgs e)
15: {
16: using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
17: {
18: decimal cartTotal = 0;
19: cartTotal = usersShoppingCart.GetTotal();
20: if (cartTotal > 0)
21: {
22: // Display Total.
23: lblTotal.Text = String.Format("{0:c}", cartTotal);
24: }
25: else
26: {
27: LabelTotalText.Text = "";
28: lblTotal.Text = "";
29: ShoppingCartTitle.InnerText = "Shopping Cart is Empty";
30: }
31: }
32: }
33:
34: public List<CartItem> GetShoppingCartItems()
35: {
36: ShoppingCartActions actions = new ShoppingCartActions();
37: return actions.GetCartItems();
38: }
39: }
40: }
When the ShoppingCart.aspx page loads, it loads the shopping cart object and then retrieves the shopping cart total by calling the GetTotal
method of the ShoppingCart
class. If the shopping cart is empty, a message to that effect is displayed.
Testing the Shopping Cart Total
Run the application now to see how you can not only add a product to the shopping cart, but you can see the shopping cart total.
- Press F5 to run the application.
The browser will open and show the Default.aspx page. - Select Cars from the category navigation menu.
Click the Add To Cart link next to the first product.
The ShoppingCart.aspx page is displayed with the order total.- Add some other products (for example, a plane) to the cart.
The ShoppingCart.aspx page is displayed with an updated total for all the products you’ve added.
Stop the running app by closing the browser window.
Adding Update and Checkout Buttons to the Shopping Cart
To allow the users to modify the shopping cart, you’ll add an Update button and a Checkout button to the shopping cart page. The Checkout button is not used until later in this tutorial series.
- In Solution Explorer, open the ShoppingCart.aspx page in the root of the web application project.
To add the Update button and the Checkout button to the ShoppingCart.aspx page, add the markup highlighted in yellow to the existing markup, as shown in the following code:
[!code-aspxMain]
1: <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ShoppingCart.aspx.cs" Inherits="WingtipToys.ShoppingCart" %>
2: <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
3: <div id="ShoppingCartTitle" runat="server" class="ContentHead"><h1>Shopping Cart</h1></div>
4: <asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
5: ItemType="WingtipToys.Models.CartItem" SelectMethod="GetShoppingCartItems"
6: CssClass="table table-striped table-bordered" >
7: <Columns>
8: <asp:BoundField DataField="ProductID" HeaderText="ID" SortExpression="ProductID" />
9: <asp:BoundField DataField="Product.ProductName" HeaderText="Name" />
10: <asp:BoundField DataField="Product.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}"/>
11: <asp:TemplateField HeaderText="Quantity">
12: <ItemTemplate>
13: <asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.Quantity %>"></asp:TextBox>
14: </ItemTemplate>
15: </asp:TemplateField>
16: <asp:TemplateField HeaderText="Item Total">
17: <ItemTemplate>
18: <%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) * Convert.ToDouble(Item.Product.UnitPrice)))%>
19: </ItemTemplate>
20: </asp:TemplateField>
21: <asp:TemplateField HeaderText="Remove Item">
22: <ItemTemplate>
23: <asp:CheckBox id="Remove" runat="server"></asp:CheckBox>
24: </ItemTemplate>
25: </asp:TemplateField>
26: </Columns>
27: </asp:GridView>
28: <div>
29: <p></p>
30: <strong>
31: <asp:Label ID="LabelTotalText" runat="server" Text="Order Total: "></asp:Label>
32: <asp:Label ID="lblTotal" runat="server" EnableViewState="false"></asp:Label>
33: </strong>
34: </div>
35: <br />
36: <table>
37: <tr>
38: <td>
39: <asp:Button ID="UpdateBtn" runat="server" Text="Update" OnClick="UpdateBtn_Click" />
40: </td>
41: <td>
42: <!--Checkout Placeholder -->
43: </td>
44: </tr>
45: </table>
46: </asp:Content>
When the user clicks the Update button, the UpdateBtn_Click
event handler will be called. This event handler will call the code that you’ll add in the next step.
Next, you can update the code contained in the ShoppingCart.aspx.cs file to loop through the cart items and call the RemoveItem
and UpdateItem
methods.
- In Solution Explorer, open the ShoppingCart.aspx.cs file in the root of the web application project.
Add the following code sections highlighted in yellow to the ShoppingCart.aspx.cs file:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7: using WingtipToys.Models;
8: using WingtipToys.Logic;
9: using System.Collections.Specialized;
10: using System.Collections;
11: using System.Web.ModelBinding;
12:
13: namespace WingtipToys
14: {
15: public partial class ShoppingCart : System.Web.UI.Page
16: {
17: protected void Page_Load(object sender, EventArgs e)
18: {
19: using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
20: {
21: decimal cartTotal = 0;
22: cartTotal = usersShoppingCart.GetTotal();
23: if (cartTotal > 0)
24: {
25: // Display Total.
26: lblTotal.Text = String.Format("{0:c}", cartTotal);
27: }
28: else
29: {
30: LabelTotalText.Text = "";
31: lblTotal.Text = "";
32: ShoppingCartTitle.InnerText = "Shopping Cart is Empty";
33: UpdateBtn.Visible = false;
34: }
35: }
36: }
37:
38: public List<CartItem> GetShoppingCartItems()
39: {
40: ShoppingCartActions actions = new ShoppingCartActions();
41: return actions.GetCartItems();
42: }
43:
44: public List<CartItem> UpdateCartItems()
45: {
46: using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
47: {
48: String cartId = usersShoppingCart.GetCartId();
49:
50: ShoppingCartActions.ShoppingCartUpdates[] cartUpdates = new ShoppingCartActions.ShoppingCartUpdates[CartList.Rows.Count];
51: for (int i = 0; i < CartList.Rows.Count; i++)
52: {
53: IOrderedDictionary rowValues = new OrderedDictionary();
54: rowValues = GetValues(CartList.Rows[i]);
55: cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ProductID"]);
56:
57: CheckBox cbRemove = new CheckBox();
58: cbRemove = (CheckBox)CartList.Rows[i].FindControl("Remove");
59: cartUpdates[i].RemoveItem = cbRemove.Checked;
60:
61: TextBox quantityTextBox = new TextBox();
62: quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
63: cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString());
64: }
65: usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
66: CartList.DataBind();
67: lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
68: return usersShoppingCart.GetCartItems();
69: }
70: }
71:
72: public static IOrderedDictionary GetValues(GridViewRow row)
73: {
74: IOrderedDictionary values = new OrderedDictionary();
75: foreach (DataControlFieldCell cell in row.Cells)
76: {
77: if (cell.Visible)
78: {
79: // Extract values from the cell.
80: cell.ContainingField.ExtractValuesFromCell(values, cell, row.RowState, true);
81: }
82: }
83: return values;
84: }
85:
86: protected void UpdateBtn_Click(object sender, EventArgs e)
87: {
88: UpdateCartItems();
89: }
90: }
91: }
When the user clicks the Update button on the ShoppingCart.aspx page, the UpdateCartItems method is called. The UpdateCartItems method gets the updated values for each item in the shopping cart. Then, the UpdateCartItems method calls the UpdateShoppingCartDatabase
method (added and explained in the next step) to either add or remove items from the shopping cart. Once the database has been updated to reflect the updates to the shopping cart, the GridView control is updated on the shopping cart page by calling the DataBind
method for the GridView. Also, the total order amount on the shopping cart page is updated to reflect the updated list of items.
Updating and Removing Shopping Cart Items
On the ShoppingCart.aspx page, you can see controls have been added for updating the quantity of an item and removing an item. Now, add the code that will make these controls work.
- In Solution Explorer, open the ShoppingCartActions.cs file in the Logic folder.
Add the following code highlighted in yellow to the ShoppingCartActions.cs class file:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using WingtipToys.Models;
6:
7: namespace WingtipToys.Logic
8: {
9: public class ShoppingCartActions : IDisposable
10: {
11: public string ShoppingCartId { get; set; }
12:
13: private ProductContext _db = new ProductContext();
14:
15: public const string CartSessionKey = "CartId";
16:
17: public void AddToCart(int id)
18: {
19: // Retrieve the product from the database.
20: ShoppingCartId = GetCartId();
21:
22: var cartItem = _db.ShoppingCartItems.SingleOrDefault(
23: c => c.CartId == ShoppingCartId
24: && c.ProductId == id);
25: if (cartItem == null)
26: {
27: // Create a new cart item if no cart item exists.
28: cartItem = new CartItem
29: {
30: ItemId = Guid.NewGuid().ToString(),
31: ProductId = id,
32: CartId = ShoppingCartId,
33: Product = _db.Products.SingleOrDefault(
34: p => p.ProductID == id),
35: Quantity = 1,
36: DateCreated = DateTime.Now
37: };
38:
39: _db.ShoppingCartItems.Add(cartItem);
40: }
41: else
42: {
43: // If the item does exist in the cart,
44: // then add one to the quantity.
45: cartItem.Quantity++;
46: }
47: _db.SaveChanges();
48: }
49:
50: public void Dispose()
51: {
52: if (_db != null)
53: {
54: _db.Dispose();
55: _db = null;
56: }
57: }
58:
59: public string GetCartId()
60: {
61: if (HttpContext.Current.Session[CartSessionKey] == null)
62: {
63: if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
64: {
65: HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
66: }
67: else
68: {
69: // Generate a new random GUID using System.Guid class.
70: Guid tempCartId = Guid.NewGuid();
71: HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
72: }
73: }
74: return HttpContext.Current.Session[CartSessionKey].ToString();
75: }
76:
77: public List<CartItem> GetCartItems()
78: {
79: ShoppingCartId = GetCartId();
80:
81: return _db.ShoppingCartItems.Where(
82: c => c.CartId == ShoppingCartId).ToList();
83: }
84:
85: public decimal GetTotal()
86: {
87: ShoppingCartId = GetCartId();
88: // Multiply product price by quantity of that product to get
89: // the current price for each of those products in the cart.
90: // Sum all product price totals to get the cart total.
91: decimal? total = decimal.Zero;
92: total = (decimal?)(from cartItems in _db.ShoppingCartItems
93: where cartItems.CartId == ShoppingCartId
94: select (int?)cartItems.Quantity *
95: cartItems.Product.UnitPrice).Sum();
96: return total ?? decimal.Zero;
97: }
98:
99: public ShoppingCartActions GetCart(HttpContext context)
100: {
101: using (var cart = new ShoppingCartActions())
102: {
103: cart.ShoppingCartId = cart.GetCartId();
104: return cart;
105: }
106: }
107:
108: public void UpdateShoppingCartDatabase(String cartId, ShoppingCartUpdates[] CartItemUpdates)
109: {
110: using (var db = new WingtipToys.Models.ProductContext())
111: {
112: try
113: {
114: int CartItemCount = CartItemUpdates.Count();
115: List<CartItem> myCart = GetCartItems();
116: foreach (var cartItem in myCart)
117: {
118: // Iterate through all rows within shopping cart list
119: for (int i = 0; i < CartItemCount; i++)
120: {
121: if (cartItem.Product.ProductID == CartItemUpdates[i].ProductId)
122: {
123: if (CartItemUpdates[i].PurchaseQuantity < 1 || CartItemUpdates[i].RemoveItem == true)
124: {
125: RemoveItem(cartId, cartItem.ProductId);
126: }
127: else
128: {
129: UpdateItem(cartId, cartItem.ProductId, CartItemUpdates[i].PurchaseQuantity);
130: }
131: }
132: }
133: }
134: }
135: catch (Exception exp)
136: {
137: throw new Exception("ERROR: Unable to Update Cart Database - " + exp.Message.ToString(), exp);
138: }
139: }
140: }
141:
142: public void RemoveItem(string removeCartID, int removeProductID)
143: {
144: using (var _db = new WingtipToys.Models.ProductContext())
145: {
146: try
147: {
148: var myItem = (from c in _db.ShoppingCartItems where c.CartId == removeCartID && c.Product.ProductID == removeProductID select c).FirstOrDefault();
149: if (myItem != null)
150: {
151: // Remove Item.
152: _db.ShoppingCartItems.Remove(myItem);
153: _db.SaveChanges();
154: }
155: }
156: catch (Exception exp)
157: {
158: throw new Exception("ERROR: Unable to Remove Cart Item - " + exp.Message.ToString(), exp);
159: }
160: }
161: }
162:
163: public void UpdateItem(string updateCartID, int updateProductID, int quantity)
164: {
165: using (var _db = new WingtipToys.Models.ProductContext())
166: {
167: try
168: {
169: var myItem = (from c in _db.ShoppingCartItems where c.CartId == updateCartID && c.Product.ProductID == updateProductID select c).FirstOrDefault();
170: if (myItem != null)
171: {
172: myItem.Quantity = quantity;
173: _db.SaveChanges();
174: }
175: }
176: catch (Exception exp)
177: {
178: throw new Exception("ERROR: Unable to Update Cart Item - " + exp.Message.ToString(), exp);
179: }
180: }
181: }
182:
183: public void EmptyCart()
184: {
185: ShoppingCartId = GetCartId();
186: var cartItems = _db.ShoppingCartItems.Where(
187: c => c.CartId == ShoppingCartId);
188: foreach (var cartItem in cartItems)
189: {
190: _db.ShoppingCartItems.Remove(cartItem);
191: }
192: // Save changes.
193: _db.SaveChanges();
194: }
195:
196: public int GetCount()
197: {
198: ShoppingCartId = GetCartId();
199:
200: // Get the count of each item in the cart and sum them up
201: int? count = (from cartItems in _db.ShoppingCartItems
202: where cartItems.CartId == ShoppingCartId
203: select (int?)cartItems.Quantity).Sum();
204: // Return 0 if all entries are null
205: return count ?? 0;
206: }
207:
208: public struct ShoppingCartUpdates
209: {
210: public int ProductId;
211: public int PurchaseQuantity;
212: public bool RemoveItem;
213: }
214: }
215: }
The UpdateShoppingCartDatabase
method, called from the UpdateCartItems
method on the ShoppingCart.aspx.cs page, contains the logic to either update or remove items from the shopping cart. The UpdateShoppingCartDatabase
method iterates through all the rows within the shopping cart list. If a shopping cart item has been marked to be removed, or the quantity is less than one, the RemoveItem
method is called. Otherwise, the shopping cart item is checked for updates when the UpdateItem
method is called. After the shopping cart item has been removed or updated, the database changes are saved.
The ShoppingCartUpdates
structure is used to hold all the shopping cart items. The UpdateShoppingCartDatabase
method uses the ShoppingCartUpdates
structure to determine if any of the items need to be updated or removed.
In the next tutorial, you will use the EmptyCart
method to clear the shopping cart after purchasing products. But for now, you will use the GetCount
method that you just added to the ShoppingCartActions.cs file to determine how many items are in the shopping cart.
Adding a Shopping Cart Counter
To allow the user to view the total number of items in the shopping cart, you will add a counter to the Site.Master page. This counter will also act as a link to the shopping cart.
- In Solution Explorer, open the Site.Master page.
Modify the markup by adding the shopping cart counter link as shown in yellow to the navigation section so it appears as follows:
[!code-htmlMain]1: <ul class="nav navbar-nav">
2: <li><a runat="server" href="~/">Home</a></li>
3: <li><a runat="server" href="~/About">About</a></li>
4: <li><a runat="server" href="~/Contact">Contact</a></li>
5: <li><a runat="server" href="~/ProductList">Products</a></li>
6: <li><a runat="server" href="~/ShoppingCart" ID="cartCount"> </a></li>
7: </ul>
Next, update the code-behind of the Site.Master.cs file by adding the code highlighted in yellow as follows:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Security.Claims;
4: using System.Security.Principal;
5: using System.Web;
6: using System.Web.Security;
7: using System.Web.UI;
8: using System.Web.UI.WebControls;
9: using System.Linq;
10: using WingtipToys.Models;
11: using WingtipToys.Logic;
12:
13: namespace WingtipToys
14: {
15: public partial class SiteMaster : MasterPage
16: {
17: private const string AntiXsrfTokenKey = "__AntiXsrfToken";
18: private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
19: private string _antiXsrfTokenValue;
20:
21: protected void Page_Init(object sender, EventArgs e)
22: {
23: // The code below helps to protect against XSRF attacks
24: var requestCookie = Request.Cookies[AntiXsrfTokenKey];
25: Guid requestCookieGuidValue;
26: if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
27: {
28: // Use the Anti-XSRF token from the cookie
29: _antiXsrfTokenValue = requestCookie.Value;
30: Page.ViewStateUserKey = _antiXsrfTokenValue;
31: }
32: else
33: {
34: // Generate a new Anti-XSRF token and save to the cookie
35: _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
36: Page.ViewStateUserKey = _antiXsrfTokenValue;
37:
38: var responseCookie = new HttpCookie(AntiXsrfTokenKey)
39: {
40: HttpOnly = true,
41: Value = _antiXsrfTokenValue
42: };
43: if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
44: {
45: responseCookie.Secure = true;
46: }
47: Response.Cookies.Set(responseCookie);
48: }
49:
50: Page.PreLoad += master_Page_PreLoad;
51: }
52:
53: protected void master_Page_PreLoad(object sender, EventArgs e)
54: {
55: if (!IsPostBack)
56: {
57: // Set Anti-XSRF token
58: ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
59: ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
60: }
61: else
62: {
63: // Validate the Anti-XSRF token
64: if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
65: || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
66: {
67: throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
68: }
69: }
70: }
71:
72: protected void Page_Load(object sender, EventArgs e)
73: {
74:
75: }
76:
77: protected void Page_PreRender(object sender, EventArgs e)
78: {
79: using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
80: {
81: string cartStr = string.Format("Cart ({0})", usersShoppingCart.GetCount());
82: cartCount.InnerText = cartStr;
83: }
84: }
85:
86: public IQueryable<Category> GetCategories()
87: {
88: var _db = new WingtipToys.Models.ProductContext();
89: IQueryable<Category> query = _db.Categories;
90: return query;
91: }
92:
93: protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
94: {
95: Context.GetOwinContext().Authentication.SignOut();
96: }
97: }
98: }
Before the page is rendered as HTML, the Page_PreRender
event is raised. In the Page_PreRender
handler, the total count of the shopping cart is determined by calling the GetCount
method. The returned value is added to the cartCount
span included in the markup of the Site.Master page. The <span>
tags enables the inner elements to be properly rendered. When any page of the site is displayed, the shopping cart total will be displayed. The user can also click the shopping cart total to display the shopping cart.
Testing the Completed Shopping Cart
You can run the application now to see how you can add, delete, and update items in the shopping cart. The shopping cart total will reflect the total cost of all items in the shopping cart.
- Press F5 to run the application.
The browser opens and shows the Default.aspx page. - Select Cars from the category navigation menu.
- Click the Add To Cart link next to the first product.
The ShoppingCart.aspx page is displayed with the order total. - Select Planes from the category navigation menu.
- Click the Add To Cart link next to the first product.
- Set the quantity of the first item in the shopping cart to 3 and select the Remove Item check box of the second item.
Click the Update button to update the shopping cart page and display the new order total.
Summary
In this tutorial, you have created a shopping cart for the Wingtip Toys Web Forms sample application. During this tutorial you have used Entity Framework Code First, data annotations, strongly typed data controls, and model binding.
The shopping cart supports adding, deleting, and updating items that the user has selected for purchase. In addition to implementing the shopping cart functionality, you have learned how to display shopping cart items in a GridView control and calculate the order total.
Addition Information
ASP.NET Session State Overview
|