Everyone knows that Asp.Net uses ViewState to save the information in the page and user-defined information between the client and the server.
In versions before 2.0, ViewState is stored in hidden controls on the page: __VIEWSTATE
We cannot change how and where ViewState is saved.
Now in 2.0, Asp.Net has opened up this feature, allowing me to customize the saving location of ViewState.
A new attribute has been added to the Page class in 2.0: PageStatePersister.
We can override this property to implement custom ViewState saving. This property returns an instance of a subclass inherited from the PageStatePersister class.
Two saving methods are provided by default in 2.0: one is to save in the page (HiddenFieldPageStatePersister), and the other is to save in the Session (SessionPageStatePersister).
The following code overrides the PageStatePersister property and saves ViewState to the Session:
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
In addition to these two default saving methods, we can inherit the PageStatePersister class to implement our own saving methods.
The following code demonstrates how to save ViewState to a file:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
/**//// <summary>
/// Summary description of CWingViewState
/// </summary>
public class CWingViewState : PageStatePersister
{
public CWingViewState(Page page):base(page)
{
}
public override void Load()
{
ReadFile();
}
public override void Save()
{
WriteFile();
}
private void WriteFile()
{
FileStream file = File.Create(@"C:CustomerViewState.CW");
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(file, base.ViewState);
file.Flush();
file.Close();
}
private void ReadFile()
{
FileStream file = File.OpenRead(@"C:CustomerViewState.CW");
BinaryFormatter bf = new BinaryFormatter();
base.ViewState = bf.Deserialize(file);
}
}
In specific pages:
protected override PageStatePersister PageStatePersister
{
get
{
return new CWingViewState(this);
}
}
Source: .Net space BLOG