Reputation: 277
I can't see what's wrong with this code:
var listShoppingCart = Session["ShoppingCart"];
foreach (var item in listShoppingCart)
{
}
I get a red line below the listShoppingCart
in the foreach loop. When I hover over the red line, the messages is that Foreach statement cannot operate on variables type 'object' because 'object' does not contain a public definition for 'GetEnumerator'
I declare the list with a session like this:
Session["ShoppingCart"] = new List<Products>();
Upvotes: 0
Views: 96
Reputation: 644
Because Session is of Type HttpSessionState
and this implements ICollection
.
Session values are stored in Dictionary<string,object>
which implements ICollection
. You need to type cast object to appropriate to enumerate over your list.
Upvotes: 0
Reputation: 29186
You need to cast the session object
var listShoppingCart = Session["ShoppingCart"] as List<Products>;
if (listShoppingCart != null)
{
// Do stuff...
}
In the above code, we get the object located in the session at key "ShoppingCart" and cast that object to a List<Products>
. If the cast cannot be done, then listShoppingCart
will be null.
Upvotes: 5