Control status and view status of ASP. net2.0

Source: Internet
Author: User

Basic Concepts

Control status-to make the control work normally, you sometimes need to store control status data. For example, if you write a custom control with different tabs that display different information, to make the control work as expected, the control needs to know which tab is selected during the round-trip process. The viewstate attribute can be used for this purpose, but developers may disable the view State at the page level to effectively interrupt the control. To solve this problem, the ASP. NET page framework discloses a new function called control state in ASP. NET 2.0. 
The controlState attribute allows the control-Specific Property Information to be kept, unlike the viewstate attribute. To use the control status, the control must call the registerrequirescontrolstate method during initialization, And Then override the savecontrolstate and loadcontrolstate methods.

View status-view status is a method used by default by ASP. NET page framework to save the page and control value between the round-trip process. When the page is displayed in HTML format, the current status and value of the page to be retained during the sending-back process will be serialized as a base64 encoded string and output to a hidden field in the view status. By implementing a custom pagestatepersister class to store page data, you can change the default behavior and store the view status to another location (such as SQL Server Database ). For an example of storing the page status on a stream instead of a hidden page field, see the example of view State persistence mechanism.

You can use the viewstate attribute of the page to save the data in the round-trip process to the web server.CodeAccess view status. The viewstate attribute is a dictionary containing key/value pairs (including view State data.

Strengths and weaknesses

View status

Advantages of view status:

· You do not need to include any server resource view status in the structure of the page code.

· Implement simple view States without any custom programming. By default, status data maintenance is enabled for the control.

· Enhanced security functions the values in the view State are hashed and compressed, and encoded for Unicode implementation. Its security is higher than that of hidden fields. 

Disadvantages of using view status

· Performance considerations because the view status is stored on the page itself, if a large value is stored, the speed of page display and page sending may be slowed down. Especially for mobile devices, the bandwidth is usually limited.

· Device restrictions mobile devices may not have enough memory to store a large amount of view status data.

· The potential security risk view State is stored in one or more hidden domains on the page. Although the view State stores data in a hash format, it can be tampered. If you directly view the page output source, you can see information in the hidden domain, which leads to potential security issues.

Control status

Advantages of using the control status:

· No server resources are required. By default, the control status is stored in the hidden domain on the page. 

· Reliability because the control status is not as close as the view status, the control status is a more reliable way to manage the control status.

· Versatility you can write custom adapters to control the storage location of control status data and control status data. 

Disadvantages of using the control status:

· Some programming is required. Although the ASP. NET page framework provides the foundation for the control state, the control state is a custom state persistence mechanism. To make full use of the control status, you must write code to save and load the control status.

Control status and view status example

This example shows how to create a custom control named indexbutton, which uses the control status to maintain key status information among multiple page requests. The control State introduced in ASP. NET 2.0 is similar to the view state, but its function is independent of the view State. Webpage developers may disable the view status of the entire page or a single control for performance reasons, but they cannot disable the control-like state. The control status is designed to store important data of a control (such as the number of pages of a page control, this data must be used for the control to work properly (even if the view status is disabled ). By default, the ASP. NET page framework stores the control status in a hidden element of the page, and the view status is also stored in the hidden element. Even if the view status is disabled or the session management status is used, the control status on the page is still transmitted to the client and then returned to the server. When sending a response, ASP. NET deserializes the content of the hidden elements and loads the control status to each control that has registered the control status.

This example illustrates a custom control that saves the status in both the control status and view status. In this example, the indexbutton control is derived from the button class and defines an index attribute, Which is saved in the control status. For comparison, indexbutton also defines an indexinviewstate attribute, which is stored in the viewstate dictionary. To understand the differences between the control status and view status, useProgramTo demonstrate the indexbutton control.

Source code of the indexbutton Control

Using system;
Using system. componentmodel;
Using system. Security. permissions;
Using system. Web;
Using system. Web. UI;
Using system. Web. UI. webcontrols;

Namespace customercontrols
{
[
Aspnethostingpermission (securityaction. Demand, level = aspnethostingpermissionlevel. Minimal ),
Aspnethostingpermission (securityaction. inheritancedemand, level = aspnethostingpermissionlevel. Minimal ),
Toolboxdata ("<{0}: indexbutton runat = \" Server \ "> </{0}: indexbutton> ")
]

Public class indexbutton: button
{
Private int indexvalue;
[
Bindable (true ),
Category ("behavior "),
Defaultvalue (0 ),
Description ("the index stored in control state .")
]

Public int Index
{
Get
{
Return indexvalue;
}
Set
{
Indexvalue = value;
}
}

[
Bindable (true ),
Category ("behavior "),
Defaultvalue (0 ),
Description ("the index stored in view state .")
]

Public int indexinviewstate
{
Get
{
Object OBJ = viewstate ["indexinviewstate"];
Return (OBJ = NULL )? 0: (INT) OBJ;
}
Set
{
Viewstate ["indexinviewstate"] = value;
}
}

Protected override void oninit (eventargs E)
{
Base. oninit (E );
Page. registerrequirescontrolstate (this );
}

Protected override object savecontrolstate ()
{
// Call the base class method to obtain the Base Value of the control status from the base class.
// If indexvalue is not equal and the control status of the base class is not null
// Use pair as a convenient data structure for efficient storage (and restoration in the loadcontrolstate method)
// Control status composed of two parts 
Object OBJ = base. savecontrolstate ();
If (indexvalue! = 0)
{
If (OBJ! = NULL)
{
Return new pair (OBJ, indexvalue );
}
Else
{
Return (indexvalue );
}
}
Else
{
Return OBJ;
}
}

Protected override void loadcontrolstate (object state)
{
If (State! = NULL)
{
Pair P = state as pair;
If (P! = NULL)
{
Base. loadcontrolstate (P. First );
Indexvalue = (INT) p. Second;
}
Else
{
If (State is int)
{
Indexvalue = (INT) State;
}
Else
{
Base. loadcontrolstate (State );
}
}
}
}
}
}

Code Discussion

The implementation of the indexbutton control illustrates three tasks. You must execute these three tasks to make the control participate in the control status:

· Override the oninit method and call the registerrequirescontrolstate method to register with the page to participate in the control status. This task must be completed for each request.

· Override the savecontrolstate method to save data in the control state.

· Override the loadcontrolstate method to load data from the control state. This method calls the base class method and obtains the Base Value of the base class to the control status. If the indexvalue field is not zero and the control status of the base class is not empty, the pair class can be used as a convenient data structure to save and restore the control status composed of two parts.

Analysis Summary

According to a series of technical references on msdn, controlState should be mainly used on custom controls. the net page framework provides the controlState attribute as a method for storing custom control data during server round-trip. "This is the original sentence on msdn, Asp. net2.0 only provides a foundation for controlState. When controlState is a custom state persistence mechanism, that is to say, the State persistence mechanism needs to be completed by your developers, rather than viewstate, it has its own default status persistence mechanism. The use of controlState in a custom control may be Microsoft's intention, so as to avoid the normal operation of the custom control after viewstate is disabled at the page level. This means that the correct running of some controls depends on its status information. if viewstate is disabled in net1.1, the control cannot run correctly. However, controlState is different after it is introduced, because controlState cannot be disabled.

So Microsoft reminded developers that "Please use the control status only for a small amount of key data that is critical to the control during the sending-back process, instead of using the control status as an alternative option for view status ". Clearly, controlState and viewstate are two things. Although they can accomplish the same task, the new controlState is neither used to replace viewstate nor to replace viewstate. Its mission is to make up for the tasks that cannot be completed by viewstate, so that developers can develop more robust controls. For example, a State of a developed custom control is crucial. Without it, the custom control cannot work normally, so the controlState should be on the stage. In addition, controlState is a custom state persistence mechanism that limits the use of controlState. You should not only register the oninit method and call the registerrequirescontrolstate Method to the page, but also rewrite saveadaptercontrolstate (), the loadadaptercontrolstate (object state) method implements what to save and how to save it. According to my understanding, if you need to save 10 different states of the control, you have to save them one by one and load them one by one. From this point, we can see the original intention of Microsoft. Isn't that obvious? If you don't need controlState, don't use it. Otherwise, how can we let our developers do everything?

This is just the foundation. As I said just now, it seems that Microsoft also said so. controlState is for custom controls. In fact, we really want to enable the controlState of basic controls, such as the label control, microsoft also allows it. This is a bit deeper, and it involves the control adapter (controladapter ). For more information, see use the control adapter to enable the controlState of the basic control. Http://sifang2004.cnblogs.com/archive/2006/06/01/415288.html

Appendix

To fully understand the above content, you must have an understanding of the following:

Pair class

Used to store the basic structure of two related objects. It is a utility class that has multiple usage methods throughout ASP. NET (such as page status management tasks or section handler configuration. In your own code, you can use the pair class to include any location of the structure of two related objects and locations that do not necessarily require data binding. The pair class does not encapsulate its object references first and second in the attribute. This class exposes them as common class fields to all call codes. 

The pair class has multiple usage methods in page state retention implementation. The most common usage is to serve as a container for both viewstate and controlState sets. In this case, the first attribute is used for viewstate, while second is used for controlState.

Pagestatepersister class

HTTP requests and responses are originally stateless. To maintain status information between HTTP requests, ASP. NET Server pages can store the page status. This state is called a view State. It contains page and control settings and data, which make pages and controls look like the last time they were submitted to the server and then returned to the client, the pages and controls that the user sees and interacts with are the same. There are several mechanisms to store view statuses between consecutive requests on the same page. The pagestatepersister abstract class indicates the base class of the state information storage mechanism.

To retain the view State on a client that does not support the existing view State persistence mechanism, you can extend the pagestatepersister class, introduce your own view State persistence method, and use the page adapter to ASP.. NET applications are configured to use different view State persistence mechanisms based on the client type that provides pages for them. Classes derived from the pagestatepersister class must override the Save abstract method to store view and control statuses in persistent media, and override the load method to extract status information. If you want to know how to write the derived class of pagestatepersister, see view State persistence mechanism.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.