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:
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:
A local variable of cartTotal is for display purposes.
.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:
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.
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:
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:
You should now be able to remove items from the cart.