ASP.NET - Client Side State Management - Control State
Join the DZone community and get the full member experience.
Join For FreeIn this post I'm going to explain what is the control state and how to use it as a part of the ASP.NET client side state management. You can read my previous posts in the state management subject in the following links:
- Client side state management introduction
- ViewState technique
- Hidden fields technique
- Query strings technique
- Cookies technique
What is Control State?
The control state is a way to save a control’s state information when the EnableViewState property is turned off. Unlike ViewState a developer can’t turn off control state. The control state can be implemented only in controls that you implement.
How to Use Control State?
Control state implementation is easy. First, override the OnInit method of the control and add the call for the Page.RegisterRequiresControlState method with the instance of the control to register. Then, override the LoadControlState and SaveControlState in order to save the required state information.
The next example shows a simple implementation for a control that saves a string as a state information:
public class ControlStateWebControl : Control{#region Membersprivate string _strStateToSave;#endregion#region Methodsprotected override void OnInit(EventArgs e){ Page.RegisterRequiresControlState(this); base.OnInit(e);}protected override object SaveControlState(){ return _strStateToSave;}protected override void LoadControlState(object state){ if (state != null) {_strStateToSave = state.ToString(); }}#endregion}
You need to remember only one thing – the control state takes away the choice to disable ViewState. You should
only use it whenever you have to keep a state information that without it your control won’t work.
Summary
To sum up the post, I showed what is the control state and how to enable it in your controls. The control state takes away the decision of a developer whether to use ViewState or not. Whenever you want to use the control state you should think whether to implement it or give the decision of how to save the state information to the developers that use your control. I prefer the second choice. In the next post in this series I’ll start to explain the server side state
management.
Opinions expressed by DZone contributors are their own.
Comments