Add a Product to Cart Programmatically

Overview

There really isn’t a need to add a product to your cart manually unless you are integrating a custom system.  For example, you might need to build a custom application on your website that adds a product outside of the Hotcakes store.  This example code will help you get started.

Requirements

The following is required in order to be able to accomplish the goals of this article:

  • Visual Studio 2012 or newer
  • Understanding of C#
  • Familiarity with building ASP.Net web applications

Getting Started

You should have a project ready to insert code to complete your application, such as a DNN CMS module.

MANUALLY ADD A PRODUCT TO THE CART

Before you can write or successfully add your code, you will first need to ensure that your project imports the following assemblies.

  • Hotcakes.Commerce.dll
  • Hotcakes.Modules.dll
  • Hotcakes.Web.dll

Now that your project has references for Hotcakes, you can ensure that your project is using the right namespaces.  Depending on your project, you will likely need other namespaces as well.

using Hotcakes.Commerce;
using Hotcakes.Commerce.Catalog;
using Hotcakes.Commerce.Extensions;
using Hotcakes.Commerce.Orders;
using Hotcakes.Commerce.Urls;

We are finally at the point of writing some code to add a product to your Hotcakes Commerce shopping cart.  Simply add this to the appropriate place in your project, such as the click event for a button, like in the example below.

protected void AddProductToCart(object sender, EventArgs e)
{

    // create a reference to the Hotcakes store
    var HccApp = HccAppHelper.InitHccApp();
    // get an instance of the product to add
    var p = HccApp.CatalogServices.Products.FindBySku("YOUR-SKU-TO-LOOK-UP");
    
    // set the quantity
    int qty = 1;

    // create a reference to the current shopping cart
    Order currentCart = HccApp.OrderServices.EnsureShoppingCart();

    // create a line item for the cart using the product
    LineItem li = HccApp.CatalogServices.ConvertProductToLineItem(p, new OptionSelections(), qty, HccApp);

    // add the line item to the current cart
    HccApp.AddToOrderWithCalculateAndSave(currentCart, li);

    // send the customer to the shopping cart page
    Response.Redirect(HccUrlBuilder.RouteHccUrl(HccRoute.Cart));

}

 

Have more questions? Submit a request

Need More Help?

Do you need more assistance with this article? Please review your support options.