Everyone knows that ASP.net uses ViewState to save information and user-defined information between the client and server.
in a version prior to 2.0, VIEWSTATE is stored in a hidden control on the page: __viewstate
We cannot change how VIEWSTATE is saved and where it is saved.
Now in 2.0, ASP.net has opened this feature, allowing me to customize the location where ViewState is saved. The
adds a property to the 2.0 page class: PageStatePersister.
We can override this property to implement a custom ViewState save. This property returns an instance of a subclass that inherits from the PageStatePersister class. Two save methods are provided by default in
2.0: One is saved in the page (Hiddenfieldpagestatepersister) and the other is saved in session (SessionPageStatePersister).
The following code overrides the PageStatePersister property and saves ViewState to the session:
protected override PageStatePersister PageStatePersister
{
get
{
return to New SessionPageStatePersister (this);
}
}
In addition to these two default save methods, we can inherit the PageStatePersister class to implement our own way of saving.
The following code demonstrates saving 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 the specific page:
protected override PageStatePersister PageStatePersister
{
Get
{
Return to New Cwingviewstate (this);
}
}
Source:. NET Space BLOG