Chapter 17. Adding Items to the Cart

As my product owner at work likes to say, this is the chapter where “the rubber meets the road.” The previous chapters have been providing the necessary setup before building the “why,” and when it comes to shopping carts, the “why” is adding the item to the cart.

The Book Details

Before a  book can be added to the cart, the book details page needs to be created. In the last chapter when the book listings were created, the link to the book sent the user to Books/Details/id. To start, the BooksController needs to be updated to add this new action. Example 17-1 contains an updated BooksController.

Example 17-1. Updated BooksController
using ShoppingCart.Models;
using ShoppingCart.Services;
using ShoppingCart.ViewModels;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;

namespace ShoppingCart.Controllers
{
  public class BooksController : Controller
  {
    private readonly BookService _bookService = new BookService();

    public BooksController()
    {
      AutoMapper.Mapper.CreateMap<Book, BookViewModel>();
      AutoMapper.Mapper.CreateMap<Author, AuthorViewModel>();
      AutoMapper.Mapper.CreateMap<Category, CategoryViewModel>();
    }

    // GET: Books
    public ActionResult Index(int categoryId)
    {
      var books = _bookService.GetByCategoryId(categoryId);

      ViewBag.SelectedCategoryId = categoryId;

      return View(
        AutoMapper.Mapper.Map<List<Book>, List<BookViewModel>>(books)
      );
    }

    public ActionResult Details(int id)
    {
      var 

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.