Previously we created the cart and added items to it. Now we'll look 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.
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.
Create a View at Views/Home/Components/ShoppingCart/Default.cs with the following:
A local variable of cartTotal is for display purposes.
.ToString("0.00") to format numbers to two decimal places.The View Component can now be added to other pages. For example in the Views/FilmDetails.cs file add:
You will need some appriopriate CSS to place this in the View.
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.
Create a View:
The above creates a table view of the cart data.
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.