Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i have a shopping cart application, if i add a item into the cart, it is visible to other users in different systems/browsers.
I need 1 user 1 cart code.

here is my code

C#
// shoppingcart.cs class
public class ShoppingCart {
	static ShoppingCart() {
		if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
		{
			Instance = new ShoppingCart();
			Instance.Items = new List<cartitem>();
			HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
		}
		else
		{
			Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
		}
	}

	public void AddItem(int productId) {
		CartItem newItem = new CartItem(productId);
		if (Items.Contains(newItem)) {
			foreach (CartItem item in Items) {
				if (item.Equals(newItem)) {
					item.Quantity++;
					return;
				}
			}
		} else {
			newItem.Quantity = 1;
			Items.Add(newItem);
		}
	}
}


// c# code
ShoppingCart.Instance.AddItem(ProductID);
Posted
Updated 14-Jul-15 22:37pm
v3

1 solution

Things that are static only have one copy that is shared by everyone and your static constructor is only called once (the first time ShoppingCart is accessed). So basically the first person to use their cart has a cart created and store in their session, and that cart is then used by everyone else via the Instance property of your class. You are basically using a singleton pattern and that is exactly what you're getting....a single cart.

You need to return Instance each time it is accessed rather than storing it the way you are.

C#
static class ShoppingCart()
{
    public static ShoppingCart Instance
    {
        get
        {
            ShoppingCart cart = null;
            if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
            {
                cart = new ShoppingCart();
                cart.Items = new List();
                HttpContext.Current.Session["ASPNETShoppingCart"] = cart;
            }
            else
            {
                cart = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
            }
            return cart;
        }
    }
}
 
Share this answer
 
Comments
Abdul Shakoor p 15-Jul-15 7:59am    
Thank you 'F-ES Sitecore' for the solution..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900