views:

158

answers:

2

Hi,

I am building a large, multi-area MVC project. (MVC 2 Beta).

I have a session wrapper class, in its own project, MySession, that looks like this:

Public Class MySession

Private Shared _userlist As String = "UserList"

Public Shared Property UserList() As IList
    Get
        If HttpContext.Current.Session(_userlist) Is Nothing Then
            Return Nothing
        Else
            Return CType(HttpContext.Current.Session(_userlist), IList)
        End If
    End Get
    Set(ByVal value As IList)
        HttpContext.Current.Session(_userlist) = value
    End Set
End Property

End Class

In a child area project, I build and save a List to Session through my wrapper:

Dim favoritesList = (From m In db.getFavorites(UserId) Select m).ToList
MySession.UserList = favoritesList

This works fine. I later retrieve the list from session into a local variable, userList:

Dim userList As IList(Of getFavoritesResult)
userList = MySession.UserList

I then ADD a new item to the LOCAL userList (and will ask the user if they want to save it):

userList.Add(New getFavoritesResult With {.Id = addApp.AppId, .DisplayText = addApp.DisplayText, ...})

Here is where the problem occurs. Immediately after the above .Add method, the local userList has the new item added, BUT the userList stored in Session ALSO contains the new item that was added to the local list.

I don't want the list updated in session unless the user wants to save the new list, and I explicitly save it.

Why does this occur, and how do I only add the item to the local list, not the one currently in session?

Thanks, this is driving me nuts!

+1  A: 

What you are storing in the session is a reference to a list. That is what you update when you update the session variable. If you really want these to be unconnected you will have to create a copy of the list when you put it in the session or create a copy when you retrieve it. I don't know the VB syntax but something like (C#):

 var newList = new List(oldList);
James Keesey
Thanks for your response. The VB syntax is what I need.
SY
+1  A: 

This is happening because both variables are referencing the same list.

So when adding via one variable, you are adding to the same list.

You need to copy the list stored in MySession, operate on the copy and when ready to save set MySession.UserList to the copy.

You can easily copy the list this way:

Dim copy As IList = new List(MySession.UserList)
Oded
Thanks, but new List(MySession.UserList) won't work. It wants a type argument List(Of ...). Any other ideas?
SY