Question background:
I have a session object that is used to store a list of object called 'CartItems'. I convert this object to an actual instance, set it to another List variable then finally clear the list. This is then sent to to a ViewBag variable and sent to a View.
The issue:
What I'm trying to do may not be possible but currently as soon as I clear the list instance of CartItems all references to this are lost aswell. Please see the following code:
public ActionResult Complete(string OrderId)
{
//Retrieve the CartItem List from the Session object.
List<CartItem> cartItems = (List<CartItem>)Session["Cart"];
//Set the list value to another instance.
List<CartItems>copyOfCartItems= cartItems;
//Set the ViewBag properties.
ViewBag.OrderId = OrderId;
ViewBag.CartItems = copyOfCartItems;
//Clear the List of CartItems. This is where the **issue** is occurring.
//Once this is cleared all objects that have properties set from
//this list are removed. This means the ViewBag.CartItems property
//is null.
cartItems.Clear();
return View(ViewBag);
}
Can I store this value without losing it after clearing the List?
When you do
ListcopyOfCartItems= cartItems;
You are creating a another variable by the name of copyOfCartItems that points to the same object cartItems. In other words cartItems and copyOfCartItems are now two names for the same object.
So when you do cartItems.clear(); you are clearing all the list items on the base object.
To get around this, make a copy of cartItems, rather than creating a reference
List<CartItems> copyOfCartItems = new List<CartItems>();
cartItems.ForEach(copyOfCartItems.Add); //copy from cartItems