View State In ASP.NET


The view state is the state of the page and all its controls. It is automatically maintained across posts by the ASP.NET framework.

When a page is sent back to the client, the changes in the properties of the page and its controls are determined, and stored in the value of a hidden input field named _VIEWSTATE. When the page is again posted back, the _VIEWSTATE field is sent to the server with the HTTP request.

The view state could be enabled or disabled for:

  • The entire application by setting the EnableViewState property in the <pages> section of web.config file.
  • A page by setting the EnableViewState attribute of the Page directive, as <%@ Page Language=”C#” EnableViewState=”false” %>
  • A control by setting the Control.EnableViewState property.

It is implemented using a view state object defined by the StateBag class which defines a collection of view state items. The state bag is a data structure containing attribute value pairs, stored as strings associated with objects.

The StateBag class has the following properties:

Properties Description
Item(name) The value of the view state item with the specified name. This is the default property of the StateBag class.
Count The number of items in the view state collection.
Keys Collection of keys for all the items in the collection.
Values Collection of values for all the items in the collection.

The StateBag class has the following methods:

Methods Description
Add(name, value) Adds an item to the view state collection and existing item is updated.
Clear Removes all the items from the collection.
Equals(Object) Determines whether the specified object is equal to the current object.
Finalize Allows it to free resources and perform other cleanup operations.
GetEnumerator Returns an enumerator that iterates over all the key/value pairs of the StateItem objects stored in the StateBag object.
GetType Gets the type of the current instance.
IsItemDirty Checks a StateItem object stored in the StateBag object to evaluate whether it has been modified.
Remove(name) Removes the specified item.
SetDirty Sets the state of the StateBag object as well as the Dirty property of each of the StateItem objects contained by it.
SetItemDirty Sets the Dirty property for the specified StateItem object in the StateBag object.
ToString Returns a string representing the state bag object.

Example

The following example demonstrates the concept of storing view state. Let us keep a counter, which is incremented each time the page is posted back by clicking a button on the page. A label control shows the value in the counter.

The markup file code is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="statedemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
   <head runat="server">
      <title>
         Untitled Page
      </title>
   </head>
   <body>

<form id="form1" runat="server">

<div>

<h3>View State demo</h3>

         
            Page Counter:
            
            <asp:Label ID="lblCounter" runat="server" />
            <asp:Button ID="btnIncrement" runat="server" Text="Add Count" onclick="btnIncrement_Click" />
         </div>

      </form>

   </body>
</html>

The code behind file for the example is shown here:

public partial class _Default : System.Web.UI.Page
{
   public int counter
   {
      get
      {
         if (ViewState["pcounter"] != null)
         {
            return ((int)ViewState["pcounter"]);
         }
         else
         {
            return 0;
         }
      }
      
      set
      {
         ViewState["pcounter"] = value;
      }
   }
        
   protected void Page_Load(object sender, EventArgs e)
   {
      lblCounter.Text = counter.ToString();
      counter++;
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s