Click here to Skip to main content
15,886,788 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.37/5 (46 votes)
23 Jul 2005GPL34 min read 303.5K   1.1K   108  
How you could improve performance of your ASP.NET projects, keeping ViewState on the server instead of on the ASPX page.
'KEEPING THE VIEWSTATE OUT OF THE ASPX PAGE
'Autor.: R�gis Daniel de Oliveira
'E-Mail: regisxp@hotmail.com
'Date..: 07/2005

'Main Reserach Source:
'http://www.eggheadcafe.com/articles/20040613.asp

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

        Debug.WriteLine(MyBase.Session.SessionID)

        '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
            Else

                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))
                    VsDataTable.Columns.Add(DbColumn)
                    PkColumn(0) = DbColumn
                    VsDataTable.PrimaryKey = PkColumn

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

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

                Else
                    '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
                Else
                    'Create a new row...
                    DbRow = VsDataTable.NewRow
                    DbRow("VSKey") = VSKey
                    DbRow("VsData") = viewState
                    DbRow("DateTime") = Date.Now
                    VsDataTable.Rows.Add(DbRow)
                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)

        Else

                'Call the normal process.
                MyBase.SavePageStateToPersistenceMedium(viewState)

            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)

            Else

                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

        Else

            '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.

License

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


Written By
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.

Comments and Discussions