Chapter 18. Updating and Deleting Cart Items

To complete a usable shopping cart experience, this chapter will extend upon the previous examples to add functionality that will allow the user to increase the quantity of an item purchased or to remove the item completely.

The Cart Details

When the cart summary was created, a link was added to view the full details. That link defined the action as the Index of the CartsController. Example 18-1 updates the CartsController to add the new Index method.

Example 18-1. Updated CartsController
using ShoppingCart.Models;
using ShoppingCart.Services;
using ShoppingCart.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ShoppingCart.Controllers
{
  public class CartsController : Controller
  {
    private readonly CartService _cartService = new CartService();

    public CartsController()
    {
      AutoMapper.Mapper.CreateMap<Cart, CartViewModel>();
      AutoMapper.Mapper.CreateMap<CartItem, CartItemViewModel>();
      AutoMapper.Mapper.CreateMap<Book, BookViewModel>();
      AutoMapper.Mapper.CreateMap<Author, AuthorViewModel>();
      AutoMapper.Mapper.CreateMap<Category, CategoryViewModel>();
    }

    // GET: Carts
    public ActionResult Index()
    {
      var cart = _cartService.GetBySessionId(HttpContext.Session.SessionID);

      return View(
        AutoMapper.Mapper.Map<Cart, CartViewModel>(cart)
      );
    }

    [ChildActionOnly]
    public PartialViewResult Summary()
    {
      var cart = _cartService.GetBySessionId(HttpContext ...

Get ASP.NET MVC 5 with Bootstrap and Knockout.js now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.