Understanding View State in ASP.NET
 
Published: 30 Jun 2006
Unedited - Community Contributed
Abstract
The ASP.NET ViewState is a powerful feature and maintains the state of pages between postbacks. This article provides a bird's eye view of View State with code examples whenever appropriate.
by Joydip Kanjilal
Feedback
Average Rating: 
Views (Total / Last 10 Days): 83135/ 156

What is ViewState and what it is not?

There are some common misconceptions about ViewState.  Let me discuss these points here for the benefit of the readers.  ViewState does not hold the controls, rather it holds the values of the form controls and their corresponding ID's that would otherwise be lost due to a post back because they do not post with the form.  ViewState is not used to hold session data or to transmit data between pages.  ViewState does not recreate the dynamically created controls of a page.  It does not restore the values to the controls after a post back operation.  Taken aback? Yes, it is true.  Even when the ViewState for a control is disabled, still the value would be retained after a post back of the page occurs, for input controls like TextBox or DropDownList.  So then, what is ViewState?  ViewState represents the state of a page when it was last processed on the web server.  It holds the values of a control that has been dynamically changed.

How does ViewState work?

All server controls have a property called ViewState.  If this is enabled, the ViewState for the control is also enabled.  Where and how is ViewState stored?  When the page is first created all controls are serialized to the ViewState, which is rendered as a hidden form field named __ViewState.  This hidden field corresponds to the server side object known as the ViewState.  ViewState for a page is stored as key-value pairs using the System.Web.UI.StateBag object.  When a post back occurs, the page de-serializes the ViewState and recreates all controls.  The ViewState for the controls in a page is stored as base 64 encoded strings in name - value pairs.  When a page is reloaded two methods pertaining to ViewState are called, namely the LoadViewState method and SaveViewState method.  The following is the content of the __ViewState hidden field as generated for a page in my system.

Listing 1

<input type="hidden" name="__VIEWSTATE"
 value="dNrATo45Tm5QzQ7Oz8AblWpxPjE9MMl0Aq765QnCmP2TQ==" />
Enabling and Disabling ViewState

By default, ViewState is enabled for all server controls.  ViewState can be enabled and disabled in any of the following ways.

·         Page Level

·         Control Level

·         Application Level

·         Machine Level

To enable or disable ViewState in the Page Level, use the following in the Page directive of the ASP.NET page.

Listing 2

<%@ Page EnableViewState ="False" %> 
or 
<%@ Page EnableViewState ="True" %>

To enable or disable ViewState at the Control Level, use the following:

Listing 3

<asp:TextBox id="txtCode" runat="server” EnableViewState="false" />
or
<asp:TextBox id="txtCode" runat="server" EnableViewState="true" />

To enable or disable ViewState in the Application Level, use the following:

Listing 4

<pages enableViewState="false" />
or
<pages enableViewState="true" />

To enable ViewState in the Machine Level, use the following:

Listing 5

<pages enableViewState="true" enableViewStateMac="true" ... />
or
<pages enableViewState="false" ... />
Saving and Restoring Values to and from the ViewState

ViewState works with the following types.

·         Primitive types

·         Arrays of primitive types

·         ArrayList and Hashtable

·         Any other serializable object

To add an ArrayList object to the ViewState use the following statements.

Listing 6

ArrayList obj = new ArrayList();
//Some code
ViewState["ViewStateObject"= obj;

To retrieve the object later use:

Listing 7

obj = ViewState["ViewStateObject"];
Performance Issues

The size of the ViewState for a page should be minimal for a better performance in page rendering.  Remember that the data in the ViewState makes a round trip and incurs more network bandwidth usage.  Therefore, ViewState should always be used judiciously.  For pages and controls that do not require a post back at all, set the EnableViewState property of the page or the control of the page to false.  It is always preferable to keep the ViewState out of the aspx page for performance improvements of the web application.  To accomplish this, the methods SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium can be used.  Use the following in the web.config or the machine.config file to disable ViewState for all the pages in a particular application or for all applications.

Listing 8

<Pages enableViewState="false"/>

Note that only controls contained within a <form runat=server> tag in the .aspx page can store ViewState.  Further, even if ViewState for a page is disabled, still the page itself saves about 20 bytes of information into ViewState to distribute post back data and ViewState values to the correct controls on post back.  So, for pages that do not post back at all, remove the runat="server" tag completely for a reduction of the page size by an amount of 20 bytes.  This reduction can be substantial for a number of such pages of the application running over the network.  ViewState should only be enabled for pages and controls that use it.  Avoid using ViewState for controls like the DataGrid and the DataRepeater as the ViewState size for these controls is quite huge.  Setting the EnableViewState properties or these controls to false would result in a huge reduction of the size of the rendered html and hence the bandwidth.

During the testing phases of an application, the ViewState size should be tested.  I am giving a code below that can detect the size of the ViewState of a page with ease.  I have created a MasterPageBase class that all the other pages in the application need to inherit.  The code for the class is as shown below.

Listing 9

public class MasterPageBase: System.Web.UI.Page
{
  protected override void OnPreRender(EventArgs e)
  {
    object viewStateObject = HttpContext.Current.Request["__VIEWSTATE"];
    if (viewStateObject == null)
      HttpContext.Current.Trace.Warn("The ViewState Size is:""0");
    else
      HttpContext.Current.Trace.Warn("The ViewState Size is:",
        HttpContext.Current.Request["__VIEWSTATE"].Length.ToString());
    base.OnPreRender(e);
  }
}
Security Issues

For security measures (to ensure that the ViewState is not tampered) one of the following two measures can be adopted.

·         Use the EnableViewStateMac property

·         Use Encryption of ViewState content

The EnableViewStateMac property ensures a Machine Authentication Check (MAC).  This should be set at the page level or in the application’s web.config file.  When set, this property appends a hash code to the ViewState before rendering.  Whenever a post back occurs, this hash code is recalculated and checked with the one that is stored in the __ViewState hidden field of the form.  It they do not match, the page is rejected, thus ensuring that the ViewState is not tampered.

To encrypt the contents of the ViewState, use the following in the machine.config file.

Listing 10

<machineKey validation="3Des" /> or <machineKey validation="SHA1"/>
ViewState Errors

There is a common ViewState error that is often encountered when transferring the control from one aspx page to another.  Let there be two aspx pages, first.aspx and second.aspx.  Let there be a text box and a submit button in the first.aspx page.  If we now use the Server.Transfer in the handler for the submit button click event in the first.aspx page to transfer the control from the page first.aspx to the page second.aspx, a ViewState error would occur.  This is because the EnableViewStateMac property of the second.aspx page is set to true by default, just as it is in all other aspx pages.  This problem can be overcome by setting the property to false in the second.aspx page.

Suggested Readings

Conclusion

ASP.NET ViewState is a great feature for web developers.  It maintains a state of a page as it moves back and forth.  This article has provided an in depth coverage of this State Management Technique of ASP.NET.  However, when using ViewState one should be well aware of the performance considerations of its usage.  It is preferable to enable tracing for a page to know the size of the ViewState for a page in the development cycle of a project.  The ViewState size should be optimized well before the application goes to deployment to avoid lengthy operations in the page load cycles of the pages of your application.



User Comments

Title: very good   
Name: hasitha
Date: 2006-12-29 8:08:54 AM
Comment:
u're explaned well.Thank u very much 4 u'r help
Title: i have one question   
Name: Satheesh
Date: 2006-12-27 2:15:56 AM
Comment:
I have two webpages in asp.net.... one page contains a textfield and a button.... i am storing the value entered in the texbox to viewstate... and i want that viewstate value to be accessed the next page's textfield control... i am getting null reference exception.... how to solve this
Title: Fine   
Name: senthil
Date: 2006-11-16 3:41:03 AM
Comment:
its really very good, now only i know how to disable viewstate in application level and machine level.
Title: Good Article   
Name: Sebin
Date: 2006-11-15 1:04:07 AM
Comment:
This is a good article. Try to post more article from JOY
Title: good explanation by joydip   
Name: chrsankar@yahoo.com
Date: 2006-11-03 4:59:55 AM
Comment:
I have also read few other articles of Joydip.He is really excellent.Please share your knowledge
Title: View State   
Name: Rakesh
Date: 2006-10-17 11:00:03 AM
Comment:
Very Useful.
Title: Its Good One   
Name: Prashant Narvekar
Date: 2006-09-23 2:10:45 AM
Comment:
its good one. i really liked it.
Title: View State   
Name: Waqas
Date: 2006-09-20 2:13:38 AM
Comment:
Nice Article! Keep it up.
Title: Understanding ViewState ASP.NET   
Name: Satya
Date: 2006-09-12 11:30:29 PM
Comment:
its really nice, you have explained it very nicely with example. Thanks a lot.
Title: great   
Name: nirwan
Date: 2006-09-08 12:48:29 AM
Comment:
great article
Title: Thank you   
Name: Keroles
Date: 2006-09-07 5:53:44 PM
Comment:
Thank you for this article
Title: viewstate   
Name: Manoj kumar singh(infotek software and system (p) ltd)
Date: 2006-09-07 2:51:21 AM
Comment:
This is an excellent article which would help for all asp.net developer
Title: very nice   
Name: jayasimha
Date: 2006-09-02 2:59:26 AM
Comment:
this article is very nice to understand the view state concept
Title: Coooooooool   
Name: ARauf
Date: 2006-08-31 1:02:04 PM
Comment:
I liked the way the author explained using examples. Nice work buddy..
ARauf from Pakistan
Title: Nice Article   
Name: Rakesh Nandrajog
Date: 2006-08-30 5:38:49 PM
Comment:
Really nice article
Title: View State   
Name: Jason Hunt
Date: 2006-08-30 10:02:59 AM
Comment:
An excellent article. Viewstate is often bloated on new developer's websites. I, myself, presumed I knew enough about it and you and certainly proved me wrong. I'm going to use your information on new development. Thank you for your article and I hope you continue to "educate" the masses.
Title: Superb   
Name: Sana
Date: 2006-08-30 9:30:07 AM
Comment:
Good article. Clearly said.
Title: hmm   
Name: Rah
Date: 2006-08-30 7:44:14 AM
Comment:
Continue with the rest of the articles
Title: More detailed explanation   
Name: rekna
Date: 2006-08-30 6:40:07 AM
Comment:
You can find a more detailed explanation of the viewstate on http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx. It's a long article, but very important to understand the real workings of viewstate, and to avoid some common mistakes!!!
Title: Understanding View State in ASP.NET   
Name: Jitu
Date: 2006-08-30 5:03:45 AM
Comment:
Really good explaination of viewstate. Author has cover almost all areas of viewstate. Best for beginer and confused programmers.
Title: viewstate   
Name: yogesh
Date: 2006-08-25 6:31:28 AM
Comment:
good
Title: Sanjay's View state   
Name: Sanjay Jaiswal
Date: 2006-08-10 6:59:41 AM
Comment:
This topic was little bit confuse d forme...but after rading this......give the whole logic behind the View State.



extremely good enough!!!!
Title: view state in asp.net   
Name: srilatha
Date: 2006-08-02 5:43:34 AM
Comment:
Hai,
The article is very informative. Thanks a lot.
Regards,
srilatha
Title: nice way   
Name: Mahesh Kumar Sharma
Date: 2006-08-01 9:53:36 AM
Comment:
This topic make little confuse me but joydip u done exelent job No body will explain in such deep..like Joydip has explained.. Thanx...
Title: good one   
Name: saurabh
Date: 2006-08-01 6:04:48 AM
Comment:
u have explained it in a very nice way. please carry it on. i am expecting some more topics to be covered from tou.
Title: great n excellent   
Name: Anonymous
Date: 2006-08-01 5:24:37 AM
Comment:
No body will explain in such deep..like Joydip has explained.. Thanx...
Title: asp.net examples   
Name: Farooq Ahmad Salmani
Date: 2006-07-14 8:24:54 AM
Comment:
I want more Examples of asp.net
Title: View State   
Name: Françoise
Date: 2006-07-11 11:55:28 AM
Comment:
This is a very good explanation the the View State concept.

Thank you very much. 07/11/2006
Title: Very Nice   
Name: Koteswara Rao
Date: 2006-07-10 10:28:56 AM
Comment:
Hi,
You have Explained very well about View state in Asp.net. It is most useful for whome Newly started programing in Asp.Net
Title: nice   
Name: venu
Date: 2006-07-08 2:52:59 PM
Comment:
hi, U explained very well.

some more topics we are expecting from U.
Title: view state   
Name: G.srinivas
Date: 2006-07-06 1:55:21 AM
Comment:
hi,
this site is very useful for the individuals who want to improove their subject.i am thankful to them who had prepared it.this site is helped me to know everything about viewstate in asp.net.oncegain thanking u
from,
srinivas.G
Title: View State   
Name: Hadi Alhendi
Date: 2006-07-04 3:10:54 AM
Comment:
I found this article very useful i want to thanks Joydip for this great article
Title: Very Good   
Name: Rajesh Medackel
Date: 2006-07-04 1:07:19 AM
Comment:
That was a very good one......:-)


Rajesh Medackel,India
Title: Do The Best   
Name: Viamlram
Date: 2006-07-04 12:53:58 AM
Comment:
You are explained well.It is derived easy to understand by the beginer.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2020 ASPAlliance.com  |  Page Processed at 2020-11-28 8:49:17 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search