ASP.NET Client Side State Management – Control State

June 13, 2008

no comments

ASP.NET Client Side State Management – Control State

In 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:

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 Members

 

        private string _strStateToSave;

 

        #endregion

 

        #region Methods

 

        protected 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
.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>