In one of my previous article ViewState Vs Caching I gave a brief introduction to ViewState and how it can be used. In this article we will look at ViewState in more detail. After reading this article you will have intermediate knowledge of the ViewState behavior.

Introduction:

In one of my previous article ViewState Vs Caching I gave a brief introduction to ViewState and how it can be used. In this article we will look at ViewState in more detail. After reading this article you will have intermediate knowledge of the ViewState behavior.

What is ViewState?

ViewState is use to save the state of the control that can change when the  POST BACK occurs. ViewState can only be useful if you are dynamically changing the state of the control and hence requires the state to be saved. Let's take a look at a simple example that shows that even though TextBox EnableViewState = false the state of the control is maintained on POST BACKS.

Here is an image of the simple user interface.

private void Page_Load(object sender, System.EventArgs e)

{

if(Page.IsPostBack == true)

{

if(txtUserName.Text.Length > 0 && txtUserName != null)

{

Label1.Text = txtUserName.Text;

}

else

{

Label1.Text = "Lost Everything";

}

}

}

private void Button1_Click(object sender, System.EventArgs e)

{

// The button click will cause a POST BACK

}

 

When you click on the asp server button it will trigger a POST BACK but the TextBox does not looses its state. The reason is simple You did not change the state of the control dynamically and hence its maintained automatically. If you look at the source of the html page generated you will notice that a hidden field is automatically created which will recover the state of the controls whose values can be lost during POST BACKS.

If you are using a calendar control than you must set the property EnableViewState=true or else the Calendar won't be able to recognize the new dates when you select them.

ViewState of a control will not stay constant but it depends on number of Postbacks you did on a page. With each PostBack the size of the page will keep on increasing. You can do a simple test of checking the ViewState of your page when you select a date from the Calendar control.

How much ViewState can hold and what are the performance issues?

Well you can run different types of tests for this purpose. But it also depends how many POST BACKS took place and how many more properties of the control got changes. Let's see that if we have 10 DropDownList on our page with 10 items each than how much will be the ViewState.

Here is a simple code that dynamically builds the DropDownLists.

private void Page_Load(object sender, System.EventArgs e)

{

// Build DropDownLists

BuildDropDownLists();

pnDDL.DataBind();

}

// Make dynamic DropDownList and Populate them

private void BuildDropDownLists()

{

// Create a ArrayList to hold 10 names

ArrayList names = new ArrayList();

names.Add("AzamSharp");

names.Add("Naila");

names.Add("Chitta");

names.Add("Jones");

names.Add("Peter");

names.Add("Saif");

names.Add("Ali");

names.Add("Hasan");

names.Add("Andy");

names.Add("Tony");

// Dynamically Add 10 DropDownLists inside a Panel Control

for(int i=1;i<=10;i++)

{

DropDownList d = new DropDownList();

d.DataSource = names;

pnDDL.Controls.Add(d);

}

}

The ViewState size of the above page is 4 KB. If the same test was performed using Datagrid control then the ViewState size would be 9.71 KB. Hence different controls spit out different ViewState sizes. Some pages also have ViewState size in MB (Mega Bytes) Ouch.

Decoding ViewState:

ViewState is encoded in BASE64 format. If you simple want to see the ViewState than you can request it using the HttpContext class.

string strV = HttpContext.Current.Request[ "__VIEWSTATE" ].ToString();

 If you are one of the curious one and want to know that how you can decode it and what does it look like in decoded form than check the code below.

// This method will Decode the ViewState

private void DecodeViewState()

{

// This code is taken from Grant Killian's Blog

// http://codebetter.com/blogs/grant.killian/archive/2003/10/20/2737.aspx

string strV = HttpContext.Current.Request[ "__VIEWSTATE" ].ToString();

byte[] arrBytes = System.Convert.FromBase64String( strV );

System.Text.ASCIIEncoding enc= new System.Text.ASCIIEncoding();

char[] charArray = new char[ enc.GetCharCount( arrBytes, 0, arrBytes.Length ) ];

enc.GetDecoder().GetChars( arrBytes, 0, arrBytes.Length,charArray, 0 );

foreach( char c in charArray )

{

TextBox1.Text += c;

}

// This code is taken from Grant Killian's Blog

// http://codebetter.com/blogs/grant.killian/archive/2003/10/20/2737.aspx

}

Creating Tamper Free ViewState: 

If you want more security on your ViewState data than you can make use of the enableViewStateMac = true. When enableViewStateMac is set to true than the ViewState is checked on POST BACK. If the sent ViewState is not same as the received ViewState than an exception is thrown.

When using enableViewStateMac = true be sure to put the entry in machine.config and use the same key in a webfarm scenario.

Conclusion:

ViewState is a very cool feature in .NET. With great features lies great responsibilities. Hence you should always make good use of the ViewState since the larger ViewState results in larger page size.

I hope you liked the article, happy coding!