In the third chapter of this series, we understand the basic knowledge of viewstate and the lifecycle of the ASPX page. Today we will continue to explain the use of the Asp.net Server Control in viewstate and the management of complex viewstate.
For simple use of viewstate, we only need to give a simple example:
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Web. UI. webcontrols;
Namespace classlibrary1
{
Public class class1: webcontrol
{
Private string _ sex;
Public String sex
{
Get
{
Return _ sex;
}
Set
{
_ Sex = value;
}
}
Public string name
{
Get
{
If (enableviewstate)
{
Object o = viewstate ["name"];
If (o! = NULL)
Return (string) O;
Else
Return string. empty;
}
Else
Return string. empty;
}
Set
{
If (enableviewstate)
Viewstate ["name"] = value;
}
}
Protected override void renderchildren (system. Web. UI. htmltextwriter writer)
{
Writer. Write ("name:" + name + "<br> ");
Writer. Write ("Sex:" + sex );
}
}
}
The effect is as follows:
When An ASPX page is submitted and returned, the loadviewstate and saveviewstate methods are executed. This is the process of parallelize and serialize the control state, which is completed through the losformatter object. The Los formatting program is used to serialize highly compressed ASCII Formats. It serializes integers, bool, and strings, and optimizes the object graphs of array, arraylist, and hashtable, the losformatter must serialize any object stored in viewstate.
The viewstate attribute belongs to the statebag class, and the modification class is a dictionary. It implements the isatemanager interface for status management. Statebag stores key-value pairs. The key-value pair is a string and the value is an object. when an object is added to the statebag instance, statebag automatically adds an additional bit to the object, it is used to store whether the object has been changed. By default, viewstate is used to manage control states. However, when a control defines complex attributes, it is impossible to use viewstate to automatically manage these attributes, therefore, you can use the istatemanager interface to manage the custom types of complex attributes. The original form of istatemanager is as follows:
Bool istrackingviewstate {Get ;}
Void loadviewstate (Object State );
Object saveviewstate ();
Void trackviewstate ();
In. in net, the control class is not inherited from istatemanager, but the control class implements the original version of istatemanager. The implementation here is not described as an example. If necessary, you can refer to ASP.. NET Server controls and component development.