Monday, November 10, 2014

C# Programming Tip - ViewState

A C# page's ViewState is a real cool place to put state information and variables you want to stick around for the lifetime of a web page.  Actually, most ASP page components save their state information in the ViewState.

Saving stuff in the ViewState is easy.  Here is an example:

ViewState["mode"] = "A"

Accessing it is easy as well:

if (ViewState["mode"].ToString() == "A") {...}

You can also do cool things like put more complex items in the ViewState like:

SomeComplexClass ComplexObject = new SomeComplexClass();
...
ViewState["ComplexObjectVS"] = ComplexObject;
...
SomeComplexClass ComplexObjectCopy = (SomeComplexClass)ViewState["ComplexObjectVS"];


So long as the object is seralizable (more on that later), you can save it in the ViewState.  There is a big drawback... space and bandwidth.  A page's ViewState is stored in the page!  So, each time the page loads, is posted or there is a postback, the entire ViewState is sent over the network.  If you want to maximize the efficiency of your page, minimize your ViewState usage.  The size of a ViewState can grow quickly if you have a large and/or complex page.

Also...  ViewStates are NOT secure.  With enough smarts a person can decode them, so don't put anything in the ViewState that you want to keep secure.

For those curious, here is what a simple ViewState looks like in a simple page:
<input id="__VIEWSTATE" name="__VIEWSTATE" type="hidden" value="/wEPDwUJNzkzMjk1ODg4D2QWAmYPZBYCAgEPZBYCAgsPDxYCHgRUZXh0BQgxLjAoZGV2KWRkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBSZjdGwwMCRNYWluQ29udGVudCRMb2dpblVzZXIkUmVtZW1iZXJNZbVBilGyAMpTuiSmFozdPPwfgNyhxhHXWwhU4O2NRdBd" />

No comments:

Post a Comment