// Finds the item that corresponds with id and decrements quantity, or removes if quantity == 1;
        protected void RemoveFromCart(int id)
        {
            // Gets list of type ProductCart from session data
            List <Models.ProductCart> ProductCartList = (List <Models.ProductCart>)Session["ProductCart"];

            // If there is a productcart item with matching id
            Models.ProductCart CartItem = ProductCartList.Find(i => i.ID == id);
            if (CartItem != null)
            {
                // If quantity > 1, decrement quantity by 1
                if (CartItem.Quantity > 1)
                {
                    System.Diagnostics.Debug.WriteLine("Decrementing ProductCart item quantity");
                    CartItem.Quantity -= 1;
                }
                // Else if quantity == 1, remove productcart item from list
                else if (CartItem.Quantity == 1)
                {
                    System.Diagnostics.Debug.WriteLine("Removing ProductCart item");
                    ProductCartList.Remove(CartItem);
                }
            }
            // Else weird error, console log
            else if (CartItem == null)
            {
                System.Diagnostics.Debug.WriteLine("Error: Could not find item to remove with id: " + id);
            }

            // Stores list back into session data
            Session["ProductCart"] = ProductCartList;

            // Removes 1 from session cart count
            Session["CartCount"] = (int)Session["CartCount"] - 1;
            System.Diagnostics.Debug.WriteLine("Cart count: " + (int)Session["CartCount"]);
        }
Example #2
0
        //Add products to cart
        protected void AddToCart(int id)
        {
            // Gets list of type ProductCart from session data
            List <Models.ProductCart> ProductCartList = (List <Models.ProductCart>)Session["ProductCart"];

            // If there exists a productcart item with matching id, increment quantity by 1
            Models.ProductCart CartItem = ProductCartList.Find(i => i.ID == id);
            if (CartItem != null)
            {
                System.Diagnostics.Debug.WriteLine("Incrementing ProductCart item quantity");
                CartItem.Quantity += 1;
            }
            // Else if null (no matching id), create productcart item with quantity 1 and add to list
            else if (CartItem == null)
            {
                System.Diagnostics.Debug.WriteLine("Creating new ProductCart item");
                CartItem = new Models.ProductCart(id, 1);
                ProductCartList.Add(CartItem);
            }

            // Stores list back into session data
            Session["ProductCart"] = ProductCartList;

            // Adds 1 to session cart count
            Session["CartCount"] = (int)Session["CartCount"] + 1;
            System.Diagnostics.Debug.WriteLine("Cart count: " + (int)Session["CartCount"]);
        }