清除会话变量值后保留它?

时间:2015-04-24 20:59:33

标签: asp.net-mvc session-variables session-state

问题背景:

我有一个会话对象,用于存储名为'CartItems'的对象列表。我将此对象转换为实际实例,将其设置为另一个List变量,然后最终清除列表。然后将其发送到ViewBag变量并发送到View。

问题:

我想要做的可能是不可能的,但是目前我一清楚CartItems的列表实例,所有对此的引用都会丢失。请参阅以下代码:

 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);
    }

清除列表后,我可以存储此值而不会丢失吗?

2 个答案:

答案 0 :(得分:1)

当你这样做时

ListcopyOfCartItems = cartItems;

您正在通过copyOfCartItems的名称创建另一个变量,该变量指向同一个对象cartItems。换句话说,cartItems和copyOfCartItems现在是同一对象的两个名称。

所以当你做cartItems.clear();您正在清除基础对象上的所有列表项。

要解决此问题,请复制cartItems,而不是创建参考

List<CartItems> copyOfCartItems = new List<CartItems>();

cartItems.ForEach(copyOfCartItems.Add); //copy from cartItems

答案 1 :(得分:0)

如果您要清除Session["Cart"],请使用Session.Remove("Cart")

相关问题