Understanding ASP.NET State management techniques-Part I

No.of Views1779
Bookmarked0 times
By  Vishal Nayan   On  12 Jul 2011 08:07:52
Tag : ASP.NET , State Management
HTTP is stateless and no matter how advance application framework is, it will always remain stateless. Which is after every web request, client get disconnected from the server and all the page objects get discarded. So there should be some technique which could store information between web requests and retrieve it when it is required.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com



HTTP is stateless and no matter how advance application framework is, it will always remain stateless. Which is after every web request, client get disconnected from the server and all the page objects get discarded. So there should be some technique which could store information between web requests and retrieve it when it is required.

Other part of this article series




What techniques are available in ASP.NET 

Image Loading

What are client side state management techniques?

1)    Cookies,
2)    Query Strings (URL),
3)    Hidden fields,
4)    View State and Control state

What client side state management mean?

When your user clicks on an URL or button or server side control, the information goes from your page to the server and then back again to the user’s web browser. How do you remember the information that is currently on the page. These are the techniques to save the information on the client side and not the server side.

What are Server side state management techniques?

1)    Session State,
2)    Application  State,
3)    Profiles
4)    Caching

What server side state management mean?

Server-side option for storing page information tends to have security than client-side options, but they can use more web server resources, which may lead to scalability issues when the size of the information store is large.

What is important to keep in mind while choosing right state management?

1)    data need to store,
2)     the length of time need to store it,
3)    the scope of data (whether it’s limited to individual users or shared across multiple requests),
4)    Additional security and performance considerations.

Note: Although it depend but we will almost always use a combination of them in the same web application (and often the same page).

Points to remember

1)    View state is used natively by the ASP.NET web controls. It allows them to retain their properties between postbacks.
2)    ViewState is page’s built in property for storing our own custom data in view state collection
3)    View state uses dictionary collection is way
4)    How to store:
ViewState["Counter"] = 1;
5)    How to retrieve:
int counter;
if (ViewState["Counter"] != null)
counter = (int)ViewState["Counter"];

Scenario 1: Storing and Retrieving control data in View State

Step 1: we will create a customer input form, like below

Image Loading

Step 2: On Save: Here on save click we will save all the control’s data into view state.

protected void cmdSave_Click(object sender, EventArgs e)
        // Save the current text.
        SaveAllText(Page.Controls, true);        
    private void SaveAllText(ControlCollection controls, bool saveNested)
        foreach (Control control in controls)
            if (control is TextBox)
                // Store the text using the unique control ID.
                ViewState[control.ID] = ((TextBox)control).Text;
                //Clear text from controls
                ((TextBox)control).Text = "";

            if ((control.Controls != null) && saveNested)
                SaveAllText(control.Controls, true);


Step 3: On Restore click, retrieve all data from view state:

protected void cmdRestore_Click(object sender, EventArgs e)
        // Retrieve the last saved text.
        RestoreAllText(Page.Controls, true);
    private void RestoreAllText(ControlCollection controls, bool saveNested)
        foreach (Control control in controls)
            if (control is TextBox)
                if (ViewState[control.ID] != null)
                    ((TextBox)control).Text = (string)ViewState[control.ID];

            if ((control.Controls != null) && saveNested)
                RestoreAllText(control.Controls, true);


Image Loading

Scenario 2: Storing and Retrieving own created custom objects in View State

Point to remember

1)    We can store our own object in view state like numeric and string types.
2)    ASP.NET converts these objects into stream of bytes so that they can be added into hidden input fields in the page. This is called Serialization
3)    To make our object serializable, we need to add a Serializable attribute before class.

Step 1: Create a class with Serializable attribute.

public class User
   public string FirstName;
   public string LastName;
   public User(string firstName, string lastName)
       FirstName = firstName;
       LastName = lastName;

Step 2: After this we can store information in view state.

// Store a customer in view state.
        User user = new User("Vishal", "Nayan");
        ViewState["CurrentUser"] = user;

Step3: When we want to retrieve , we will need to cast this;

// Retrieve a customer from view state.
        User user;
        user = (User)ViewState["CurrentUser"];

Step 4

Its important and mandatory that all member variables of the class must use serializable data types. Any nonserializable data type must be decorated with the NonSerialized attribute (which means it is simply ignored during the serialization process).

Step 5

if the Serializable attribute isn’t present, the object isn’t serializable, and you won’t be able to store it in view state.

Why not to user View State?

View state is ideal because it doesn’t take up any memory on the server and doesn’t restrict any arbitrary usage limits (such as a time-out).

1)    Any important data should be not stored in view state, because hackers can access and modify that information when page is posted back.
2)    In case we need to share data with multiple pages, view state cannot be used.
3)    When we need to store large amount of data  , avoid View state

How to see View State Value for page

Step 1: Enable trace to see the value;

<%@ Page Language="C#" Trace="true" AutoEventWireup="true" CodeFile="ViewState.aspx.cs" Inherits="ViewState" %>


Image Loading

How to secure View State

Hashing:  A hash code is a cryptographically strong checksum.

How it work: When the page is posted back, ASP.NET recalculates the checksum and ensures that it Matches. If a malicious user changes the view state data, ASP.NET will be able to detect the change,And it will reject the postback.

Status: enabled by default

How to disable it

<%@ Page Language="C#" EnableViewStateMac="false" />


    <pages enableViewStateMac="false" />

Encryption: prevent users from getting any view state information

Status: Auto by default.

How to enable it

<%@ Page Language="C#" ViewStateEncryptionMode="Always" />

This is end of your 1st part of reading Hope you enjoyed it.

Sign Up to vote for this article
About Author
Vishal Nayan
Occupation- Software Engineer
Member Type-Junior
Joined date-02 Apr 2011
Home Page-
Blog Page-http://vishalnayan.wordpress.com
Vishal is a seasoned professional with hand on experience on Microsoft technologies. He always look for challenging assignment that allows him to learn newer technologies while utilizing his experience of project development and software engineering ethics. In spare time vishal can be found reading business and political personalities, acts as critics at columnist , writing poetries, bird watching , singing ,cooking. He have strong interests in Indian business and political arena and want to be an active one someday. He is also a part-time trainer on framework , WCF and Silverlight. reach him at vishalnayan@gmail.com
Other popularSectionarticles
    It is a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. A session is defined as the period of time that a unique user interacts with a Web application. Active Server Pages (ASP) developers who wish to retain data for unique user sessions can use an intrinsic feature known as session state.
    Published Date : 02/Jun/2011
    It store global objects that can be accessed by any client.It supports the same types what session state support which are of type objects, retains information on the server, and uses the same dictionary-based syntax. Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object.
    Published Date : 09/May/2011
    Http protocol is stateless, so we need to maintain state on Client side or Server side. For this time I am going to discuss about the maintaining state on Server Side with one programming practice.
    Published Date : 10/Jan/2011
    Now web application framework, no matter how advanced, can change that HTTP is a stateless protocol. So inherently we should also forget our users, but unfortunately we cannot.ASP.Net Framework provides us features by which we can maintain states of your users.
    Published Date : 26/Jun/2010
    There is Lots of ways and Techniques Are available to Manage you State on Web in Aspnet
    Published Date : 06/May/2010
There is no comments for this articles.
Leave a Reply
Display Name:
(not display in page for the security purphase)
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top