Back to list
Views:   9.7K
Replies:  1

ViewState in Session

I was looking at the "Patterns in Action". Had one question. I have configured SessionState as "Out of Process" in SQL Server. If I configure ViewState to use "Session", then would that information get persisted to SQL Server as well since I have configured to persist Session information to SQL Server? Or do I have to write the code to persist to database separately.
Raju Joseph, Jul 08, 2010
Reply 1
This is how to persist the viewState to the database (not the session). 

If you want to put the viewstate in the session you will need to make a sessions table or run the .net utility to do it for you. Here is a good article on that

You will need to create a database table. I think there is a utility that will do it for you but I would roll my own.

Create Table ViewState (


 Value Text NOT NULL,

 Expires NOT NULL


The id is an identity so you know you have a unique number acrossed all of your servers in the garden
The id is an int instead of a guid because the size of the guids will shread you pages with the huge numbers of inserts and deletes
The Expires is added so expired viewstates can be purged.

Next you will need to create a base page that all of your pages inherit.

Then add the method that saves the viewstate to the basepage:

protected override void SavePageStateToPersistenceMedium(Object viewState)
        DateTime expires = DateTime.Now.AddMinutes(Session.Timeout);
        string key = [ save a serialized version of view state and the expires date to database here and return the id ]
        ClientScript.RegisterHiddenField("_VIEWSTATE_KEY", key);

Then add the method that retreives it:

protected override object LoadPageStateFromPersistenceMedium()
        int? key = (int?)Request.Form["_VIEWSTATE_KEY"];
        if (key != null) return [ load the viewstate out of database based on the key and deserialized it and then delete it]
        return null;
Aaron Burton, Jul 09, 2010
Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.