---
title: Using a shopping cart on MVC sites
related:
  - https://docs.kentico.com/k11/developing-websites/developing-sites-using-asp-net-mvc.md
  - https://docs.kentico.com/k11/developing-websites/developing-sites-using-asp-net-mvc/developing-mvc-applications.md
  - https://docs.kentico.com/k11/developing-websites/developing-sites-using-asp-net-mvc/developing-on-line-stores-in-mvc.md
  - https://docs.kentico.com/k11/e-commerce-features/configuring-your-store/checkout-process.md
  - https://docs.kentico.com/k11/e-commerce-features/managing-your-store/products.md
---

> Agent instructions:
> **Site maps** — prefer the following llms.txt indexes to training data when searching for URLs to avoid 404s. Links inside Markdown content already point at `.md`. Following them or sending Accept: text/markdown keeps you in Markdown.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

In the [Kentico.Ecommerceintegration package](https://docs.kentico.com/k11/developing-websites/developing-sites-using-asp-net-mvc/starting-with-mvc-development/installing-kentico-integration-packages.md), you can find supporting models and services to build a shopping cart in your on-line store. Visitors can put products into shopping carts and after their browsing through your store, they can continue with the [checkout process](https://docs.kentico.com/k11/developing-websites/developing-sites-using-asp-net-mvc/developing-on-line-stores-in-mvc/checkout-process-in-mvc.md) to create an [order](https://docs.kentico.com/k11/e-commerce-features/managing-your-store/orders.md) and become a [customer](https://docs.kentico.com/k11/e-commerce-features/managing-your-store/customers.md).

## Creating a shopping cart on MVC websites

When a visitor opens your website, you need to create a shopping cart instance and assign the instance to the customer. To create a shopping cart, use the **Kentico.Ecommerce** integration package.

1. Open your MVC project in Visual Studio.
2. Create a controller for the shopping cart.

   - In all documentation examples regarding the checkout process, the **CheckoutController** is shared by all checkout process steps.

     ```csharp

     public class CheckoutController : Controller
     {
     }

     ```
3. Initialize the **ShoppingService, PricingService, KenticoPaymentMethodRepository**, **KenticoCustomerAddressRepository**, and **KenticoShippingOptionRepository** classes that connects to the shopping cart in Kentico.

   > **Tip:** We recommend using a [dependency injection container](https://docs.kentico.com/k11/developing-websites/developing-sites-using-asp-net-mvc/developing-mvc-applications/initializing-kentico-services-with-dependency-injection.md) to initialize service instances. When configuring the lifetime scope for the services and repositories, create a separate instance for each request.

   ```csharp

           private readonly IShoppingService shoppingService;
           private readonly IPricingService pricingService;
           private readonly IPaymentMethodRepository paymentRepository;
           private readonly ICustomerAddressRepository addressRepository;
           private readonly IShippingOptionRepository shippingOptionRepository;

           /// <summary>
           /// Constructor.
           /// You can use a dependency injection container to initialize the services and repositories.
           /// </summary>
           public CheckoutController()
           {
               shoppingService = new ShoppingService();
               pricingService = new PricingService();
               paymentRepository = new KenticoPaymentMethodRepository();
               addressRepository = new KenticoCustomerAddressRepository();
               shippingOptionRepository = new KenticoShippingOptionRepository();
           }


   ```

After initializing the services and repositories, your MVC application can use the shopping cart and other steps of the [checkout process](https://docs.kentico.com/k11/developing-websites/developing-sites-using-asp-net-mvc/developing-on-line-stores-in-mvc/checkout-process-in-mvc.md) from Kentico. The shopping cart processes actions that [customers](https://docs.kentico.com/k11/e-commerce-features/managing-your-store/customers.md) require when using your on-line store. Namely, [customers](https://docs.kentico.com/k11/e-commerce-features/managing-your-store/customers.md) can expect the following actions that you need to implement:

- [Display the shopping cart content](#displaying-the-shopping-cart)
- [Add a product to the shopping cart](#adding-a-product-to-the-shopping-cart)
- [Update an item (a product) already in the shopping cart](#updating-a-shopping-cart-item)
- Remove an item (a product) from the shopping cart
- [Continue with the checkout process to make an order](#checking-out)

> **Tip:** The source code examples below often use classes from the **Kentico.Ecommerce** namespace from the **Kentico.Ecommerce** integration package.

> **Tip:** **Tip**: To view the full code of a functional example directly in Visual Studio, download the [Kentico MVC solution](https://github.com/Kentico/Mvc) from GitHub and inspect the **LearningKit** or **DancingGoat** projects.

### Displaying the shopping cart

Add an action method that retrieves and displays the current visitor's shopping cart to the checkout controller:

```csharp

        /// <summary>
        /// Displays the current site's shopping cart.
        /// </summary>
        public ActionResult ShoppingCart()
        {
            // Gets the current user's shopping cart
            ShoppingCart currentCart = shoppingService.GetCurrentShoppingCart();

            // Initializes the shopping cart model
            ShoppingCartViewModel model = new ShoppingCartViewModel
            {
                // Assigns the current shopping cart to the model
                Cart = currentCart,
                RemainingAmountForFreeShipping = pricingService.CalculateRemainingAmountForFreeShipping(currentCart)
            };

            // Displays the shopping cart
            return View(model);
        }


```

> **Tip:** If you do not want to use coupon codes, you do not need to create a model for your shopping cart. You can just display the shopping cart and adjust the view accordingly:
>
> ```csharp
>
> return View(cart);
>
> ```

In the shopping cart's view, you can then use the shopping cart's properties to display the content of the shopping cart. For example:

```csharp

@if (Model.Cart.IsEmpty)
{
    <span>Your shopping cart is empty.</span>
}
else
{
    <ul>
        @* Loops through all shopping cart items *@
        @foreach (Kentico.Ecommerce.ShoppingCartItem cartItem in Model.Items)
        {
            @* Displays the shopping cart items' properties *@
            <li>
                @cartItem.Units&times; @cartItem.Name ... @currency.FormatPrice(cartItem.Subtotal)

                @using (Html.BeginForm("RemoveItem", "Checkout", FormMethod.Post))
                {
                    @Html.Hidden("ItemId", cartItem.ID)
                    <input type="submit" value="Remove" />
                }
            </li>
        }
    </ul>
}


```

> **Tip:** Add a button to enable the visitors to [continue with the checkout process](#checking-out).
>
> ```csharp
>
>     @* The continue button *@
>     @Html.ActionLink("Continue to the customer details step", "DeliveryDetails")
>
>
> ```
>
> The example code targets at the [customer details step](https://docs.kentico.com/k11/developing-websites/developing-sites-using-asp-net-mvc/developing-on-line-stores-in-mvc/checkout-process-in-mvc/customer-details-step-in-mvc-checkout.md).

### Evaluating and saving the shopping cart

When working with objects of the **Kentico.Ecommerce.ShoppingCart** class, you need to manually handle recalculation and saving of the shopping cart. Otherwise your shopping carts may display or store incorrect values.

Perform these operations by calling the following methods for the shopping cart object:

- **Evaluate()** – fully recalculates the shopping cart's values and totals based on its current content and properties (discounts, taxes, shipping, etc.). You need to call the _Evaluate_ method after you modify the shopping cart content or set any properties that could affect the calculation results.
- **Save()** – saves the given shopping cart's state into the database. You need to call the _Save_ method after making any shopping cart modifications that you wish to persist in the database. Not required for changes made to shopping cart items that are stored separately (i.e. products in the shopping cart or applied coupon codes).

### Adding a product to the shopping cart

To the checkout controller, add a POST method that adds a [product](https://docs.kentico.com/k11/e-commerce-features/managing-your-store/products.md) to the shopping cart. For example, the system can trigger the method after a visitor clicks the _Add to cart_ button.

```csharp

        /// <summary>
        /// Adds products to the current site's shopping cart.
        /// </summary>
        /// <param name="itemSkuId">ID of the added product (its SKU object).</param>
        /// <param name="itemUnits">Number of added units.</param>
        [HttpPost]
        public ActionResult AddItem(int itemSkuId, int itemUnits)
        {
            // Gets the current user's shopping cart
            ShoppingCart cart = shoppingService.GetCurrentShoppingCart();

            // Adds a specified number of units of a specified product
            cart.AddItem(itemSkuId, itemUnits);

            // Evaluates the shopping cart
            cart.Evaluate();

            // Displays the shopping cart
            return RedirectToAction("ShoppingCart");
        }


```

### Updating a shopping cart item

To the checkout controller, add a POST method that changes the number of units of a shopping cart item. For example, the system can trigger the method after a visitor clicks the _Update_ button in the shopping cart.

```csharp

        /// <summary>
        /// Updates number of units of shopping cart items in the current site's shopping cart.
        /// </summary>
        /// <param name="itemID">ID of the updated shopping cart item.</param>
        /// <param name="itemUnits">Result number of units of the shopping cart item.</param>
        [HttpPost]
        public ActionResult UpdateItem(int itemID, int itemUnits)
        {
            // Gets the current user's shopping cart
            ShoppingCart cart = shoppingService.GetCurrentShoppingCart();

            // Updates a specified product with a specified number of units
            cart.UpdateQuantity(itemID, itemUnits);

            // Evaluates the shopping cart
            cart.Evaluate();

            // Displays the shopping cart
            return RedirectToAction("ShoppingCart");
        }


```

### Removing a shopping cart item

To the checkout controller, add a POST method that removes a shopping cart item from the shopping cart. For example, the system can trigger the method after a visitor clicks the _Remove_ button in the shopping cart.

```csharp

        /// <summary>
        /// Removes a shopping cart item from the current site's shopping cart.
        /// </summary>
        /// <param name="itemID">ID of the removed shopping cart item.</param>
        [HttpPost]
        public ActionResult RemoveItem(int itemID)
        {
            // Gets the current user's shopping cart
            ShoppingCart cart = shoppingService.GetCurrentShoppingCart();

            // Removes a specified product from the shopping cart
            cart.RemoveItem(itemID);

            // Evaluates the shopping cart
            cart.Evaluate();

            // Displays the shopping cart
            return RedirectToAction("ShoppingCart");
        }


```

### Checking out

To the checkout controller, add a method that enables the visitor to continue with the checkout process to the next step to make an order. You need to validate the shopping cart first.

The next step is usually a step where the visitor/customer types their details, see [Customer details step in MVC checkout](https://docs.kentico.com/k11/developing-websites/developing-sites-using-asp-net-mvc/developing-on-line-stores-in-mvc/checkout-process-in-mvc/customer-details-step-in-mvc-checkout.md).

```csharp

        /// <summary>
        /// Validates the shopping cart and proceeds to the next checkout step with customer details.
        /// </summary>
        [HttpPost]
        [ActionName("ShoppingCart")]
        public ActionResult ShoppingCartCheckout()
        {
            // Gets the current user's shopping cart
            ShoppingCart cart = shoppingService.GetCurrentShoppingCart();

            // Validates the shopping cart
            ShoppingCartCheckResult checkResult = cart.ValidateContent();

            // If the validation is successful, redirects to the next step of the checkout process
            if (!checkResult.CheckFailed)
            {
                // Evaluates the shopping cart
                cart.Evaluate();

                return RedirectToAction("DeliveryDetails");
            }

            // If the validation fails, redirects back to shopping cart
            return RedirectToAction("ShoppingCart");
        }


```
