ViewState Persistance

Using ViewState is an amazingly easy way to persist state, but it does quickly add weight to a page, especially when a developer is already using Gridview or has a number of server controls on the page. Of course, with more and more users moving to broadband connections, the weight issue falls away. ViewState appears as a hidden form field _VIEWSTATE on the client side.

Notes!

- ViewState is case sensitive so ViewState["myKey"] != ViewState["mykey"]

- ViewState can create a lot of encoded text at the top of your page, creating potential issues with search engine spiders and your page’s SEO.

- While the ViewState value appears as a long string of random ASCII characters on the client side. It is easy to decode on the client side by default. The Page directive can be used to encrypt the string, but it increases server load, so it is best practice to keep sensitive data out of the ViewState.

A web user control combined with ViewState can be an effective way to store user information over an entire web site. A class can be set up to read info from a database and then store the info inside the ViewState. The class must be made serializable to allow storage of information in the ViewState. This is simple to comply with, by inserting the C# code [Serializable] command at the top of the class after the using statements and before the namespace of the class.

T o use the class and insert the properties in the ViewState only take a couple lines of code using C#:

ClassName holder = new ClassName();

this.ViewState["NameofClass"] = holder;

Pulling the data out of the ViewState is only a few more lines of code:

ClassName holder2 = new ClassName();

holder2 = this.ViewState["NameofClass"] as NameofClass;

Then populate the web user control:

label1.Text = holder2.property (add a .ToString if the value pulled out is not a string.

The web user control can be placed on any number of pages, and the ViewState will be utilized to provide a ’stateful’ option for web developers. The ViewState connection will need to be run on the Page_Load event of the user control, because the ViewState isn’t formed until after the _Init events. You will also want to check the status of the ViewState in the user control to ensure the database isn’t called when the info is already stored in ViewState.

The code to check is even simpler:

if (this.ViewState["ItemName"] == null) or if !(this.ViewState["ItemName"])

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)