"State" Rights? Dear God! Is it a Confederacy All Over Again? (
Page 1 of 5 )
ASP.NET 1.0's ViewState provided plenty of power and control. Things get even better in 2.0 with the arrival of ControlState, which is only available for Webcontrols and for not for the page. Miguel Castro explains.
If you ask any seasoned ASP.NET developer what single thing gives ASP.NET its tremendous competitive edge and ease of development, most would probably answer, the state mechanism. Yet, if you ask about the ASP.NET's Achilles' heel, you may also hear, the state mechanism. How can that be?
ViewState can be your best friend or your worst enemy. On the positive side, even though we had a lot of power and control with ViewState in ASP.NET 1.0/1.1, things get even better in 2.0 with the arrival of ControlState. Unlike ViewState, ControlState is only available for Webcontrols and for not the page. However, you need to exercise good judgment when using ViewState, as with all environment features and development aids. It has a few nasty surprises.
ADVERTISEMENT
Before I show how ControlState works, let's go over some often-missed fundamentals on the basics of state management using ViewState. If you've ever been confused with the details of how state management works in ASP.NET, sit back and read.
The ViewState Variable
State management, in its simplest form, is handled by placing values into the ViewState variable. This variable, of type StateBag, automaticallys persist its values into a hidden textbox called __ViewState; perhaps you've seen it when you view the source of a rendered ASPX page. Inserting values into ViewState is done in a typical key-value pair fashion, and looks like this:
ViewState("LastNameCaption") = Value
Not much to it, huh? For ease of use, this type of assignment is usually placed within a property statement within a page or a control, and would look like this:
Public Property LastNameCaption() As String
Get
If CType(ViewState("LastNameCaption"), Object) Is Nothing Then
Return "Last name:"
End If
Return CType(ViewState("LastNameCaption"), String)
End Get
Set(ByVal Value As String)
ViewState("LastNameCaption") = Value
End Set
End Property
As you can see, setting and retrieving the ViewState variable replaces the typical "member variable/public" property design that normal objects usually get. Okay, so let's talk a little bit about the ViewState variable and where it comes from.