Manage States for Controls

To maintain a consistent state for web server controls, ASP.NET provides you two powerful ways. As HTTP is stateless in its nature, we should use workarounds to ensure that our work and data are available between request.  ASP.NET has two answers for this problem: View State and Control State.

Control’s View State is exactly the same hidden field on the generated HTML page as the page’s. In fact, Control State also uses the same hidden field.

What should you store in View State: as View State can be turned off for a page, you shouldn’t rely on it. The data or properties that are critical for your control (for example, the current index of a page) should be stored in Control State. Data related to the layout of a control should be stored in View State, but you should limit yourself. Pushing too much information into View State can result in slower postbacks, because View State information is send to the client, and then it’s sent back to the server. Sometimes it’s even encrypted, which makes the whole process more slower. Also, sensitive data shouldn’t be stored in View State, because it travels to the client’s computer, where it can be tampered with.

In Control State, you should store very little and critical information for your controls. Working with control state is designed to be confusing and hard, just to make sure you won’t over use it. First you should register your control as something which requires control state in the OnInit method of it. Then you need to override the SaveControlState and LoadControlState methods to save values and load them back respectively, using the Pair class. Your control implementation should look similar to the following:

public string theData {get; set;}
protected override void OnInit(EventArgs e)
protected override object SaveControlState()
Object baseState = base.SaveControlState();
return  new Pair (baseState, theData);
protected override void LoadControlState(object sate)
Pair p = state as Pair;
string theData = (string) p.Second;

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: