Adding coupon code fields to MVC checkout processes

The Kentico E-commerce Solution provides coupon codes for several types of discounts:

Customers that obtained a coupon code are eligible to some discount (based on configuration of the discount).

When building a checkout process on an MVC site, you may want to place a coupon code text box for customers. They can type their coupon code into a specified text box and apply the coupon. The system then validates whether the coupon code provides a discount. In a Kentico MVC project, the Kentico.Ecommerceintegration package holds the coupon code information.

To place the coupon code field on your MVC site:

  1. Open your MVC project in Visual Studio.

  2. Add a method for setting and validation of coupon codes to your controller using the SetCouponCode method.

    1. Add a method that sets and validates the coupon code:

      
      
      
               /// <summary>
               /// Applies the specified coupon code to the specified shopping cart.
               /// </summary>
               /// <param name="cart">Shopping cart to which the coupon code is applied.</param>
               /// <param name="couponCode">Coupon code to be applied.</param>
               [HttpPost]
               private bool ApplyCouponCode(ShoppingCart cart, string couponCode)
               {
                   // Assigns the coupon code to the shopping cart
                   cart.CouponCode = couponCode;
                   cart.Save();
      
                   // Returns whether the code is valid (i.e. whether the coupon code applies any discount or is empty)
                   return cart.HasUsableCoupon;
               }
      
      
      
       
    2. Call the method from the POST action of displaying the shopping cart.

  3. In the shopping cart’s view, create a form with a coupon code text box and an apply button.

    
    
    
     @* Coupon code text box and apply button *@
     @using (Html.BeginForm("ShoppingCart", "Checkout", FormMethod.Post))
     {
         <input type="text" name="CouponCode" value="@Model.CouponCode" />
         <input type="submit" name="ApplyCouponCode" value="Apply" />
     }
    
    
    
     

    Add a button for continuing with the next checkout process step to the form. This ensures that the customer does not need to click the apply button to use the coupon.

The system now accepts coupon codes typed during the checkout process and customers can get their discounts.