[ASP.NET 1.x] Storing ViewState in Session State

A very good tip from MSDN magazine (July 2006). If you want to keep your ASP.NET pages lighter why not keeping lengthy ViewState in memory instead of the page.

Tested, works perfectly well. One question, is it scalable? I mean what's happens with hundreds of simultaneous users?

The magazine has the C# code, so here we go with the VB.Net override functions:

UPDATE: Well it's a bad idea, I got too much timeout issues, see the comment below for more explanations.

Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
        Dim key As String = Request.RawUrl + "_VIEWSTATE"
        Dim state As Object = Session(key)
        If state Is Nothing Then
            Return MyBase.LoadPageStateFromPersistenceMedium()
        Else
            Return state
        End If
End Function
Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal viewState As Object)
        Dim key As String = Request.RawUrl + "_VIEWSTATE"
        Session(key) = viewState
End Sub

2 Comments

  • It's really unfortunate that MSDN Magazine published this method. It's an insanely bad idea to store ViewState contents using in-memory Session. In-memory Session objects are subject to timeout and memory pressures. In-memory Session only scales on a single server and should only ever be used for small applications with a very predictable population of users. It certainly does not scale across servers. That's why .NET 2.0 has filesystem and SQL storage providers for Session. But of course if you stuff ViewState into File or SQL Session then you're serializing the data twice.

  • This methods will also cause some big issues with some controls.
    If you open another window with "file / new / window" in IE, then the 2 windows will share the same session.
    So you navigate throught different ways in those 2 windows, you'll have the controls from the two pages that will share the same data, that's something you wouldn't expect.

Comments have been disabled for this content.