Implementing View State properties

By design HTTP, the protocol used to request and deliver web pages, is stateless. What that means is that the server does not keep track of requests you made to the browser. As far as the server is concerned, each request for a page is an entirely new one and is not related to any previous request you may have made.

This of course causes issues if you need to maintain data for a specific user. To overcome these problems, web developers have a number of solutions available, including session state, cookies and hidden form fields. ASP.NET Web Forms has been hiding much of this complexity by implementing a concept called View State. Controls (including the Page class itself) can read from and write to the View State collection to maintain data across postbacks. Controls such as Label use this mechanism to send their values to and from the browser, maintaining them across postbacks.

In this article you'll see how to leverage View State to store your own values as well.

Maintaining State Using View State Properties

If you have data stored in the Page class that is not part of a control, this data gets lost after a postback. For example, a simple field or a property does not maintain its value as the Page class that contains this data is recreated each time the page loads, both on the initial request as well as on subsequent postbacks. To see how this can be problematic, consider this example:

Partial Class WithoutViewState Inherits System.Web.UI.Page Dim counter As Integer Protected Sub PostbackButton_Click(sender As Object, e As System.EventArgs) _ Handles PostbackButton.Click counter = counter + 1 Label1.Text = counter.ToString() End Sub End Class C#
using System; public partial class WithoutViewState : System.Web.UI.Page { private int counter; protected void PostbackButton_Click(object sender, EventArgs e) { counter++; Label1.Text = counter.ToString(); } }

When you run this code, every time you click the button, the label will display 1. The reason for this is that after each postback the Page is recreated and counter is initialized to zero again.

Fixing this is pretty easy. All you need to do is convert your field or property to a View State property. The Get method (get in C#) gets its data from the ViewState property of the containing Page class, or returns a default value when no value is present in View State (which is the case for the first request). The Set method (set in C#) stores the value in View State. Here's the same page, but now rewritten so Counter (renamed to match the naming conventions for properties) is now able to maintain its value across postbacks.

Partial Class WithViewState Inherits System.Web.UI.Page Protected Sub PostbackButton_Click(sender As Object, e As System.EventArgs) _ Handles PostbackButton.Click Counter = Counter + 1 Label1.Text = Counter.ToString() End Sub Public Property Counter As Integer Get Dim o As Object = ViewState("Counter") If Not o Is Nothing Then Return CType(o, Integer) Else Return 0 End If End Get Set(ByVal Value As Integer) ViewState("Counter") = Value End Set End Property End Class C#
using System; public partial class WithViewState : System.Web.UI.Page { protected void PostbackButton_Click(object sender, EventArgs e) { Counter++; Label1.Text = Counter.ToString(); } public int Counter { get { object counter = ViewState["Counter"]; if (counter != null) { return (int)counter; } else return 0; } set { ViewState["Counter"] = value; } } }

This code uses the Page's ViewState property to store its data. Data you assign to this property is serialized and stored in a hidden field called __VIEWSTATE in the page. For the sample above, that field looks like this:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
	 GThk/CgB5NdiYE7ihUhzVOVuNmLk+zuF14uID9rnQyGIQ==" />

Note that the original code has remained exactly the same (except for renaming the Counter variable which is optional.

ASP.NET sends this hidden field to the browser on each request and the browser sends it back on each postback. At the server, ASP.NET is then able to extract the values stored in this field. This means that the Get method in the Counter property is able to successfully retrieve the number that it stored on a previous request using the Set method. When there's no value, the Get method of the property returns 0 which is the standard default value for an Integer (an int in C#). You could modify this default value to whatever default you want to initialize the Counter property on the first request.


Values you store in View State are serialized and stored in the hidden __VIEWSTATE field. This adds to the size of the page which in turn affects download time and performance. Don't use View State to store large objects such as DataSets. However, storing a few simple values, like the Counter property in this example is a good use of View State.


Download the code for the samples shown in this article (VB and C#)

Where to Next?

Wonder where to go next? You can post a comment on this article.

Doc ID 570
Full URL
Short cut
Written by Imar Spaanjaars
Date Posted 07/29/2012 16:04


Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the Doc ID of the document.

(Plain text only; no HTML or code that looks like HTML or XML. In other words, don't use < and >. Also no links allowed.