asp.net mvc - Keep a session variable value after it has been cleared? -
question background:
i have session object used store list of object called 'cartitems'. convert object actual instance, set list variable clear list. sent to viewbag variable , sent view.
the issue:
what i'm trying may not possible clear list instance of cartitems references lost aswell. please see following code:
public actionresult complete(string orderid) { //retrieve cartitem list session object. list<cartitem> cartitems = (list<cartitem>)session["cart"]; //set list value instance. list<cartitems>copyofcartitems= cartitems; //set viewbag properties. viewbag.orderid = orderid; viewbag.cartitems = copyofcartitems; //clear list of cartitems. **issue** occurring. //once cleared objects have properties set //this list removed. means viewbag.cartitems property //is null. cartitems.clear(); return view(viewbag); } can store value without losing after clearing list?
when
listcopyofcartitems= cartitems;
you creating variable name of copyofcartitems points same object cartitems. in other words cartitems , copyofcartitems 2 names same object.
so when cartitems.clear(); clearing list items on base object.
to around this, make copy of cartitems, rather creating reference
list<cartitems> copyofcartitems = new list<cartitems>(); cartitems.foreach(copyofcartitems.add); //copy cartitems
Comments
Post a Comment