April 12, 2011

Control State in ASP.NET

Description:
    Sometimes a control needs to store some essential data to work properly. For this purpose we can use view state to store the information. But one of the disadvantages of using view state is that it has the functionality that it can be turned off at control level as well as page level. So you cannot trust on view state to store control’s essential data as you have no control of the page where your control is going to be placed, you have to take care of this to preserve the data required to function control properly. To handle this situation ASP.NET page framework provides a feature called Control State.
    Control state works similar to view state but you cannot disable it like you allowed doing for view state. And it shares the same location with view state in the page to store its data (__VIEWSTATE hidden field).

Implementation:
To implement this you have to follow the following steps.
  1. Override the OnInit() Method and invoke the RegisterRequiredsControlState() method to register the page to participate in control state.
  2. Override the SaveControlState() method to save the control state data.
  3. Override the LoadControlState() method to load the control state data.
Example:
 
Advantages:
     1.       Other user using your control cannot disable the control state.
     2.       Disabling view state will not affect the control.
     3.       Server resource is not required as data is stored on the page.
Disadvantages:
     1.       It is not fully ready made; you have to write a little bit of code to implement this.
     2.       Like the same as view state, if large amount of data is stored then it will affect page performance as these data will travel with the page.

No comments:

Post a Comment

Your comments are valuable.