Building a Shopping Cart Part Two

Menu
Menu

Displaying and Managing the Shopping Cart

Types of Cart Display

Previously we created the cart and added items to it. Now we'll look at a couple of ways of displaying the information to the user. Firstly we'll have a basic cart summary that can be viewed on multiple pages and this will link to a more complex cart management page that would allow the cart to be amended. To allow the cart summary to appear on multiple pages will require a View Component. A View Component represents a chunk of reusable code that can be included inside another view.

Creating a View Component

Create a new folder at the route of the application called ViewComponents. In this folder create a class file called ShoppingCartViewComponent.cs. The naming convention is important here, ensure the file end ...ViewComponent.cs

Create a model at Models/CartItem.cs as follows:

VIEWCOMPONENT: ViewComponents/ShoppingCartViewComponent.cs

The ViewComponent is set up to return a deserialized String from the session.

Creating the View for the ViewComponent

Create a View at Views/Home/Components/ShoppingCart/Default.cshtml with the following:

VIEW: Views/Home/Components/ShoppingCart/Default.cshtml

A local variable of cartTotal is for display purposes.

Tip: Notice the use of .ToString("0.00") to format numbers to two decimal places.

Adding the View Component to other Views

The View Component can now be added to other pages. For example in the Views/FilmDetails.cshtml file add:

VIEW: Views/FilmDetails.cshtml

Repeat the above for Views/AllFilms.cshtml and the Views/Search.cshtml views.

Building a Controller for the Manage Cart Page

The Manage Cart page will require a straight-forward Controller and View.

CONTROLLER: Controllers/HomeController.cs

As with the ViewComponent the session is deserilized and made available to the view.

Building a View for the Manage Cart Page

Create a View:

VIEW: Views/Home/ManageCart.cshtml

The above creates a table view of the cart data.

Allow for the Removal of Cart Items

The Manage Cart View has a form that calls an Action of RemoveCartItem using POST. In the HomeController.cs set up the Action as follows:

CONTROLLERS: Controllers/HomeController.cs

You should now be able to remove items from the cart.