There are 120 guests and 0 members online. Who is online?

home  »  articles  »  ASP.NET Viewstate and ControlState

ASP.NET Viewstate and ControlState

change text size: A A A

Published on 3/19/2009 by vivek_iit

Difference between ViewState and ControlState

ViewState is the technique by which an ASP.NET Web page can save changes to the state of a Web Form across postbacks, without using Session or any other server variable. The ASP.NET runtime stores viewstate inside a hidden element in the redendered page's HTML, using BASE64 encoding. You can encrypt the viewstate too by simply modifying basic settings in the web.config file. Control state, introduced in ASP.NET version 2.0, is similar to view state but functionally independent of view state. We can disable viewstate for a page or for an individual control for performance but control state cannot be disabled. Control state is used for storing a control's essential data  that is needed on postback to enable the control to function even when view state has been disabled. Control state is stored in the same hidden element in which view state is stored. 

Most ASP.NET developers think that the ASP.NET ViewState is responsible for holding the values of controls such as TextBoxes so that they are retained even after postback. But this is not the case.

I'll explain this with an example. Let's understand this with a simple ASP.NET web project in C#, VS 2005/2008.

Open a new ASP.NET Web Application, and on the WebForm, place the following controls accordingly:

Place a web server TextBox control, an HTML server text box control (normal HTML input box with runat=server), a normal HTML input control, and a web server Label control. Name the four controls as:

  • txtWebServerTest
  • txtHtmlServerTest
  • txtHtmlTest
  • lblTest

Set the Text/Value property to “Initial Text” for the above three TextBoxes, and set the Text property of the Label control to “Initial Label Value”.

Set the EnableViewState property to false for the first and the last controls.

Beneath these controls, place two Button controls and set their text as “Change Label’s Text” and “Postback to Server”. On the button click event handler of the first button, write the following code:

private void btnChangeLabel_Click(object sender, System.EventArgs e)
{
    lblTest.Text = "Label's Text Changed";
}


There is no code on the second button’s Click event. It just submits the page to the server.

Now run this application. You can see the initial texts in the controls as you have set.

Now, change the text in all TextBoxes and set them to “Changed Text”. Now click the Post to Server button. What happens is that the first two textboxes retain their values, in spite of the ViewState property being set to false. But the last textbox, which is a simple HTML input control, loses the modified value when the page is reloaded.

Most developers would have expected all three textbox controls to lose their modified values (“Changed Text”), and after page re-loading, they expect “Initial Value” being written on all textboxes as we had disabled the ViewState.

The reason for this behavior is that ViewState is not responsible for storing the modified values for controls such as TextBoxes, dropdowns, CheckBoxList etc., i.e., those controls which inherit from the IPostBackDataHandler interface. After Page_Init(), there is an event known as LoadViewState, in which the Page class loads values from the hidden __VIEWSTATE from the field for those controls (e.g., Label) whose ViewState is enabled. Then the LoadPostBackData event fires, in which the Page class loads the values of those controls which inherit from the IPostBackDataHandler interface, (e.g., TextBox) from the HTTP POST headers.

Now, start the application again, and this time, click the “Change Label’s Text” button. When the page reloads, you will see that the programmatic change (made by our code in the event handler of the button’s Click event) is visible. But if not you click Post to Server button (or any other button which simply submits the form and reloads the page), the changed text of the lable is lost i.e., we don’t see the Label’s text changed to “Label's Text Changed”. Instead, we see the initial value of the Label again. This is because the Label control does not inherit from the IPostBackDataHandler interface, and hence will not get loaded from forms POST data. So the ViewState is responsible for persisting its value across postbacks, and since it has been disabled, the Labele loses its value after clicking the “Change Label’s Text” button.

Now enable the ViewState for the Label control, and you can see the modified value (“Label's Text Changed”) after clicking the same button.

While it is true that the ViewState does not contain any user changed values for a control which is being posted back the ViewState does contain the value(s) which have been added to the control in code (likedropdownlist) or the value from the previous postback (in the case of a text box).

Consider a dropdown list added to the page with 3 items added in the ASPX page. In the Page_Load 2 more items are added to the dropdown


Page_Load
{
  if (!IsPostBack)
  {
    DropDownList1.Items.Add("D");
    DropDownList1.Items.Add("E");
  }
}


These items will never be added except on the first load of the page, if you set EnableViewState=false when the page loads you will have 5 items. If the page posts back then when it re-renders there will be only the 3 items which are added from the ASPX.

A Text control works the same way except that the result isn't as noticeable it's not often that you want to work with the previous post back value but it does come up, expecially when dealing with dynamic controls based on user input. So while disbaling viewstate for controls such as textboxes, we have to be careful because sometimes we do need viewstate enabled to retain properties such as readonly for a textbox! 

 

To rate this article please register or login

Author

vivek_iit vivek_iit (Member since:11/27/2008)
I am one of the administrators at CodeAsp.Net and I love programming, architecting solutions, code reviews, teaching and writing about ASP.NET.

Comments (4)

  • developer3366 7/23/2009 7:03:06 PM by:  developer3366
    Nice article but I have a question: You said " Instead, we see the initial value of the Label again. " Where does it get this values from if it's not available in Viewstate?
  • developer3366 7/23/2009 7:02:04 PM by:  developer3366
    You said: Instead, we see the initial value of the Label again. Where is it getting this from if nothing is saved? It's not in viewstate?
  • 7/3/2009 2:14:38 AM by: 
    Hi Vivek, Very Nice Article.
  • 5/25/2009 12:26:19 AM by: 
    Hello Vivek, The article was really nice. Infact sometimes, we just take cetain properties just for granted. Your article really helped me understand my concepts well. Thanks a lot.

Post a comment

Comment  (No HTML)   

Type the characters:
 *
 

Related articles

Join CodeAsp.Net for FREE Today!

It's fast, easy and free! Submit articles, get your own blog, ask questions & give answers in the forums, and become a better developer, faster.

enter your email address:

Latest Articles RSS Feed

Latest articles

.
  • how to change Visual Studio's default browser
    12/15/2009
    how to change Visual Studio's default browser
  • Access dropdownlist inside the gridview
    12/10/2009
    Hi Friends, Many times we came cross the requirement when we need to access the dropdownlist's selectedindexchanged event inside the gridview, like in a shopping cart changing the item's quantity or binding the other dropdown based on the first dropdown.
  • JavaScript Expandable / Collapsible Panel Control
    12/4/2009
    This is the approach that I have adopted to develop Expandable / Collapsible Panel Control through JavaScript. Please report bugs, errors and suggestions to improve this control.
  • JavaScript ListBox Control
    12/3/2009
    This is my approach to develop custom JavaScript ListBox control. Although it is only a subset of existing HTML ListBox element, it is more user friendly than the existing one. It can be further customized for different requirements. Please let me know ab...
  • Multiple File Upload User Control
    11/27/2009
    I have tried my best to make this user control code error free. I will most welcome suggestions for further improvement in this user control. I have tested this user control on various browsers and it works fine.
  • Slide-Show User Control
    11/26/2009
    So, this is my approach to implement an ASP.NET slide show using the DataList. I have tried my best to keep it bug free. I will most welcome suggestions and criticism for further improvements of this user control. I have tested this user control on variou...
  • Implement: Paging in Repeater or Datalist Control
    11/18/2009
    As we all knows that Repeater and DataList does not have auto paging support technique like Gridview or Datagrid, but we can achieve this through PagedDataSource. By using PagedDataSource we can implement paging in Repeater or DataList. Now in our mind t...
  • JavaScript Context Menu Control
    11/6/2009
    So this is my approach. I was working for a long time to create C# like event handlers for JavaScript classes and finally, I’ve done it. Please let me know of any bugs and suggestions to improve this context menu control.
  • Maintaining States of Selected CheckBoxes in Different Pages inside the GridView
    11/4/2009
    So this is my solution. If you have some other ideas about this functionality, please share them with me.
  • GridView Rows Navigation Using Arrow (Up/Down) Keys
    11/4/2009
    I have tried my best to make this code error free. Suggestions and criticism for further improvements of this code are most welcome.

More Articles