Click here to Skip to main content
12,898,516 members (64,627 online)
Click here to Skip to main content


107 bookmarked
Posted 23 Jul 2005

Keep ASP.NET ViewState out of ASPX Page for Performance Improvement

, 23 Jul 2005 GPL3
How you could improve performance of your ASP.NET projects, keeping ViewState on the server instead of on the ASPX page.
'Autor.: R�gis Daniel de Oliveira
'Date..: 07/2005

'Main Reserach Source:

Imports System.Configuration.ConfigurationSettings
Imports System.Diagnostics

Public Class VSPage
    Inherits System.Web.UI.Page
    Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal viewState As Object)

        Dim VSKey As String 'String that will hold the Unique Key used to reference this ViewState data


        'Create the key based on the SessionID, on the Request.RawUrl 
        'and on the Ticks representated by the exact time while the page is being saved
        VSKey = "VIEWSTATE_" & MyBase.Session.SessionID & "_" & Request.RawUrl & "_" & Date.Now.Ticks.ToString

        'Check if the ServerSideViewState is Activated
        If UCase(AppSettings("ServerSideViewState")) = "TRUE" Then

            'Check were we will save the ViewState Data
            If UCase(AppSettings("ViewStateStore")) = "CACHE" Then

                'Store the ViewState on Cache
                Cache.Add(VSKey, viewState, Nothing, Date.Now.AddMinutes(Session.Timeout), _
                 Cache.NoSlidingExpiration, Web.Caching.CacheItemPriority.Default, Nothing)

                'The ViewStateData will be Saved on the SESSION

                Dim VsDataTable As DataTable
                Dim DbRow As DataRow

                'Check if the ViewState DataTable are on the Session
                If IsNothing(Session("__VSDataTable")) Then

                    'No, it's not. Create it...
                    Dim PkColumn(1), DbColumn As DataColumn
                    VsDataTable = New DataTable("VState") 'Create the DataTable

                    'Column 1 - Name: VSKey - PrimaryKey
                    DbColumn = New DataColumn("VSKey", GetType(String))
                    PkColumn(0) = DbColumn
                    VsDataTable.PrimaryKey = PkColumn

                    'Column 2 - Name: ViewStateData
                    DbColumn = New DataColumn("VSData", GetType(Object))

                    'Column 3 - Name: DateTime
                    DbColumn = New DataColumn("DateTime", GetType(Date))

                    'The ViewState DataTable is already on the UserSession
                    VsDataTable = Session("__VSDataTable")

                End If

                'Check if we already have a ViewState saved with the same key. 
                'If yes, update it instead of creating a new row. (This is very dificult to happen)
                DbRow = VsDataTable.Rows.Find(VSKey)

                If Not IsNothing(DbRow) Then
                    'Row found!!! Update instead of creating a new one...
                    DbRow("VsData") = viewState
                    'Create a new row...
                    DbRow = VsDataTable.NewRow
                    DbRow("VSKey") = VSKey
                    DbRow("VsData") = viewState
                    DbRow("DateTime") = Date.Now
                End If

                'Check if our DataTable is OverSized...
                If Convert.ToInt16(AppSettings("ViewStateTableSize")) < VsDataTable.Rows.Count Then
                    Debug.WriteLine("Deleting ViewState Created On " & DbRow(2) & ",ID " & DbRow(0))
                    VsDataTable.Rows(0).Delete() 'Delete the 1st line.
                End If

                'Store the DataTable on the Session.
                Session("__VSDataTable") = VsDataTable

            End If

            'Register a HiddenField on the Page, that contains ONLY the UniqueKey generated. 
            'With this, we'll be able to find with ViewState is from this page, by retrieving these value.
            RegisterHiddenField("__VIEWSTATE_KEY", VSKey)


                'Call the normal process.

            End If

    End Sub
    Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object

        'Verifica se o ServerSideViewState est� ativado
        If UCase(AppSettings("ServerSideViewState")) = "TRUE" Then

            Dim VSKey As String 'ViewState UniqueKey
            VSKey = Request.Form("__VIEWSTATE_KEY") 'Request the Key from the page and validade it.

            If Not VSKey.StartsWith("VIEWSTATE_") Then
                Throw New Exception("Invalid VIEWSTATE Key: " & VSKey)
            End If

            'Verify which modality was used to save ViewState
            If UCase(AppSettings("ViewStateStore")) = "CACHE" Then
                Return Cache(VSKey)


                Dim VsDataTable As DataTable
                Dim DbRow As DataRow
                VsDataTable = Session("__VSDataTable")
                DbRow = VsDataTable.Rows.Find(VSKey)

                If IsNothing(DbRow) Then
                    Throw New Exception("VIEWStateKey not Found. Consider increasing the ViewStateTableSize parameter on Web.Config file.")
                End If

                Return DbRow("VsData")

            End If


            'Return the ViewState using the Norma Method
            Return MyBase.LoadPageStateFromPersistenceMedium()

        End If

    End Function

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


About the Author

Régis Daniel de Oliveira
Web Developer
Brazil Brazil
Régis Daniel is currently living in Itaúna, MG, Brazil. He works with programming since 1999 and actualy works as IT Manager on a wholesaler company. He has experiency as Oracle DBA, and also worked as a PalmOS developer using CodeWarrior with C/C++.
Now a days he works on .NET Framework, developing solutions on Visual Basic.NET and ASP.NET. During his spare time, he likes reading books, watching movies and pratices some outdoor activities, like Trekking and Camping.

You may also be interested in...

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170424.1 | Last Updated 23 Jul 2005
Article Copyright 2005 by Régis Daniel de Oliveira
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid