Thursday, April 9, 2009

ViewState, Twins, and Triplets!

This is a great article on ViewState and how it works that I found after a co-worker made a comment about optimizing our project by disabling the ViewState property on some of our project's web page controls.

public string NavigateUrl
{
get
{
string text = (string) ViewState["NavigateUrl"];
if (text != null)
return text;
else
return string.Empty;
}
set
{
ViewState["NavigateUrl"] = value;
}
}

(You can view the decompiled source code for a .NET assembly by using a tool like Reflector.)

So when a page control's properties are accessed, as is the case with a HyperLink's NavigateUrl property, the ViewState is actually what gets checked because it saves a snapshot of each control's persisting data. The ViewState is of type System.Web.UI.StateBag, and it stores name-value pairs for all of the page's controls, and can be accessed syntactically the same way in which a Hashtable would.

The article also highlighted two (detestably adorable) classes, the Pair and Triplet classes!

"The Pair and Triplet are two classes found in the System.Web.UI namespace, and provide a single class to store either two or three objects. The Pair class has properties First and Second to access its two elements, while Triplet has First, Second, and Third as properties."

Although I personally would have named the Pair class as the Twin class instead. Oh well.

No comments: