ASP.NET Web Forms Programming Web Forms Web Forms State Management
In the Web Forms page framework, each control on a Web Forms page, including the page itself, has a ViewState property that is inherited from the base Control class. ViewState is used by the page framework to automatically save with each round trip the state of the page and its current property values, and the state of server controls and their base property values.
The ViewState is stored in the page as a hidden form field. When the page is posted, one of the first tasks performed by page processing is to restore the view state.
Aside from, and independent of page and control values, ViewState enables authors to save application-specific values that need to be preserved automatically between round trips to the server.
NOTE: In order to use the ViewState property, the page must have a <form runat="server"
> control. For usage recommendations, see State Management Recommendations.
- Create and store a new element in the ViewState property.
ViewState [ "color" ] = "slategray";
ViewState ( "color" ) = "slategray" |
|
C# |
VB |
NOTE: The data must be in a format compatible with view state. For example, to store a DataSet in view state, it must first be converted to a string representation.
- Get the value of an element by specifying its name. Cast the object in view state to the type that it needs to be.
The following example shows how you can retrieve a value stored earlier under the ViewState name "color". Note that the value must be cast to a string.
string strColor;
strColor = ( string ) ViewState [ "color" ];
Dim strColor as String
strColor = CStr ( ViewState ( "color" ) ) |
|
C# |
VB |
The following example shows you can save a DataSet in view state and then retrieve it. To save it, you create a string representation of it using the DataSet’s WriteXml method. When retrieving the dataset, you cast it to a StringReader class and then call the DataSet’s ReadXml method.
if ( Page.IsPostBack ) {
System.IO.StringReader sr = new System.IO.StringReader
( ( string ) ( ViewState [ "dsCustomers" ] ) );
DsCustomers1.ReadXml ( sr );
}
else {
myAdapter.Fill ( DsCustomers1 );
System.IO.StringWriter sw = new System.IO.StringWriter ( );
DsCustomers1.WriteXml ( sw );
ViewState [ "dsCustomers" ] = sw.ToString ( );
}
If Page.IsPostBack Then
Dim sr as New System.IO.StringReader _
( CStr ( ViewState ( "dsCustomers" ) ) )
DsCustomers1.ReadXml ( sr )
Else
myAdapter.Fill ( DsCustomers1 )
Dim sw as New System.IO.StringWriter ( )
DsCustomers1.WriteXml ( sw )
ViewState ( "dsCustomers" ) = sw.ToString ( )
End If |
|
C# |
VB |
Note that you can also store state information in the Session and Application objects.
Introduction to Web Forms State Management State Management Recommendations