Reputation: 1407
I have used this example to create a shopping cart : http://net.tutsplus.com/tutorials/other/build-a-shopping-cart-in-aspnet/
Its a good example, it stores the shoppingcart in the Session["cart"] state and it should all work fine.
BUT it doesn't. Event if close the browser, or try different browsers, it still maintains state?!?!
Here is the constructor + the add to cart method:
public List<CartItem> Items { get; private set; }
// Readonly properties can only be set in initialization or in a constructor
public static readonly ShoppingCart Instance;
// The static constructor is called as soon as the class is loaded into memory
static ShoppingCart()
{
// If the cart is not in the session, create one and put it there
// Otherwise, get it from the session
if (HttpContext.Current.Session["MPBooksCart"] == null)
{
Instance = new ShoppingCart();
Instance.Items = new List<CartItem>();
HttpContext.Current.Session["MPBooksCart"] = Instance;
}
else
{
Instance = (ShoppingCart)HttpContext.Current.Session["MPBooksCart"];
}
}
// A protected constructor ensures that an object can't be created from outside
protected ShoppingCart() { }
public void AddItem(int book_id)
{
// Create a new item to add to the cart
CartItem newItem = new CartItem(book_id);
// If this item already exists in our list of items, increase the quantity
// Otherwise, add the new item to the list
if (this.Items.Contains(newItem))
{
foreach (CartItem i in Items)
{
if (i.Equals(newItem))
{
i.Quantity++;
return;
}
}
}
else
{
newItem.Quantity = 1;
Items.Add(newItem);
}
}
May you please advise on what the issue might be?
I've read for about 2 hours regarding session state and everywhere it says it should be volatile when closing broser, but in this case it isn't.
Regards, Alex
Upvotes: 1
Views: 3346
Reputation: 5277
I am not so sure about using a Singleton pattern to hold an instance of a session. If you think about it the session will need to be unique for each user and each browser that accesses the website. The Singleton pattern creates a single global unique instance. I don't know how much asp.net you have done but, just in case you are fairly new to asp.net a session will be unique to a specific browser instance. That means that each browser accessing the Session["MPBooksCart"] will access their own unique copy of the data. By default an asp.net session will hold its data for 20 minutes (this can be configured in the database). If I was writing a shopping cart I would probrably just work directly with a cart table and cartitems table in a database. A very good example of a storefront website is Rob Connery's MVC Samples App. This is an ASP.Net MVC application so if you aren't familiar with MVC you may find this a little bit hard to follow.
Upvotes: 1