Reputation: 3424
I want to be able to use the query
select * from cart
and save that in an List. IN my class CartItem, I have defined attributes of id, name ,quantity, and totalprice
Now i want to save it in a session, so that when the user logs in the shopping cart. his previous Cart items should be loaded through a sql query and saved it into a session.
Right now i have the following code, but it does not load the previous cart of a customer from the database.
The mistake I was doing was loading the cart from the sql database every time the customer clicked on view cart. Which is wrong. i should keep it in a session.
public class ShoppingCart
{
#region ListCart
public static String cid;
public List<CartItem> Items { get; private set; }
public static SqlConnection conn = new SqlConnection(connStr.connString);
#endregion
#region CartSession
public static readonly ShoppingCart Instance;
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"];
}
}
This is my cart class which holds the product added to the cart.
public class CartItem : IEquatable<CartItem>
{
#region Attributes
public int Quantity { get; set; }
public static SqlConnection conn = new SqlConnection(connStr.connString);
private int _productId;
public int ProductId
{
get { return _productId; }
set
{
_product = null;
_productId = value;
}
}
private Product _product = null;
public Product Prod
{
get
{
if (_product == null)
{
_product = new Product(ProductId);
}
return _product;
}
}
public string Name
{
get { return Prod.ProductName; }
}
public string Description
{
get { return Prod.Description; }
}
public float UnitPrice
{
get { return Prod.UnitPrice; }
}
public float TotalPrice
{
get { return UnitPrice * Quantity; }
}
#endregion
#region Methods
public CartItem(int productId)
{
this.ProductId = productId;
}
public bool Equals(CartItem item)
{
return item.ProductId == this.ProductId;
}
#endregion
}
Upvotes: 0
Views: 718
Reputation: 30902
I think I can guess what the problem is, different users somehow use the same shopping cart...
public static readonly ShoppingCart Instance;
This line declares a static instance of the ShoppingCart
class. What that means in ASP.NET is that it's data is shared accross the application. Since the application is running on the server, and is servicing more that one user at a time, that instance is shared across all users. If you have two users, once an item is added it'll be added to everyone's shopping cart, and each time a new user comes along, the shopping cart will be reset.
So, unless you have really, trully application-wide static data, don't use static data in asp.net applications.
Upvotes: 2