Another round of
difficult confrontation with ViewState. This time we will try to save it in the SQL Server database.
A little repeat the theory. We have a
PageAdapter class, the use of which can "adapt" an aspx page to a specific browser (in our case, to all). Using this adapter, you can override the functionality for loading and saving ViewState (using the
GetStatePersister method).
So, the procedure is:
- create a simple structure in the database for storing the ViewState:

We also create stored procedures for getting, saving, and clearing (obsolete) ViewState;
')
- we inherit the
PageStatePersister class, in it we override the Load and Save methods to implement loading and saving the ViewState respectively:
namespace SqlStatePersister
{
public class SqlPageStatePersister : PageStatePersister
{
private Page _page;
public SqlPageStatePersister( Page page)
: base (page)
{
_page = page;
}
public override void Load()
{
// ViewState
}
public override void Save()
{
// ViewState
}
}
}
* This source code was highlighted with Source Code Highlighter .
- we inherit the PageAdapter class, in it we override the GetStatePersister method so that it returns an instance of the class defined in the first step:
namespace SqlStatePersister
{
public class SqlPageAdapter : PageAdapter
{
public override PageStatePersister GetStatePersister()
{
return new SqlPageStatePersister( Page );
}
}
}
* This source code was highlighted with Source Code Highlighter .
- using the .browser-file “adapt” the page:
< browsers >
< browser refID ="Default" >
< controlAdapters >
< adapter controlType ="System.Web.UI.Page" adapterType ="SqlStatePersister.SqlPageAdapter" />
</ controlAdapters >
</ browser >
</ browsers >
* This source code was highlighted with Source Code Highlighter .
- at will we add buns, for example, the gzip-compression functional before saving to the database;
- create a scheduler (for example, SQL Server Job), which will clean the table from outdated ViewState;
- PROFIT!
The
example (VS 2010 solution, .NET 4) uses the
AdventureWorks database, which replaced Northwind as an example. For the application to work, appSettings requires the presence of a ViewStateCompress setting, which is set to 1 if gzip compression is needed, or 0 if not needed. In the connectionStrings section, you also need a connection string to the database in which the ViewState will be stored (in my example it is a separate database, created by running the install.sql script from the solution).
Thanks for attention! If you need more detailed comments on the project, I am at your service;)
PS Based on
Store ViewState in the Database instead of the Hidden Form Field and
ViewState Compression .