SqlViewState - The Path To Better ViewState Storage
A while ago, several colleges of mine were having a terrible time with the loading times of some pages of their web application. Come to find out, they were suffering from ViewState bloat. ViewState was something I always tried to stay away from in the past because of this factor. Sure, it was very helpful but I found ways around it.
However, I have come to a change of heart to realize ViewState is a wonderful thing, except that it can still cause pages to suffer from the ViewState bloat symptom. You could be a frugal programmer and control the ViewState more by only allowing certain pieces into but there are times when you want to store large amounts of data in the ViewState. For example, you may have search results that were very costly to find and you need to persist the results for paging.
So, I started looking at different devices to store the ViewState in. I thought of putting it into our session state which is stored in a SQL database, but the timeout settings for session and page view state were very different in some cases and this method would not allow for the flexibility that is required. Or perhaps someone avoids session state like the plague or it isn't stored in a central repository in case of a web farm approach.
The decision was easy, I would create a small table that stores ViewState in it much like the session state. I actually put the table and procedures in the same database as our session state just for consistency. It was also easy to script the job that cleans up timed out ViewState since we already had one for the session state. Here is the install script you will need to run to setup the table, stored procedures, and job to clean up the table every so often.
To keep it simple I simply look for one value, the connection string to use in an appSetting key called “ViewStateConnectionString“. Optionally, you can define a “ViewStateTimeout“ with a value being the number of minutes to wait before clearing the ViewState data. You can also set this value per page if you have certain pages that will live longer on the client before a post back. If the connection string is not provided, it will not affect the ViewState processing as it will resort to the old method. The following is an example of the appSettings section.
<appSettings>
<add key="ViewStateConnectionString" value="Server=(local);Database=ASPState;Trusted_Connection=yes;"/>
<add key="ViewStateTimeout" value="20"/>
</appSettings>
Here is the class that you will need to inherit from if you want to take advantage of this ViewState change, provided for you in the wonderful language of C#. I apologize for the lack of comments, hopefully it is self explanatory.