What is View State and How it Works in ASP.Net

Background 

A web application is stateless. That means that a new instance of a page is created every time when we make a request to the server to get the page and after the round trip our page has been lost immediately. It only happens because of one server, all the controls of the Web Page is created and after the round trip the server destroys all the instances. So to retain the values of the controls we use state management techniques.
 
State Management Techniques 

They are classified into the following 2 categories:


 
Now I am explaining what View State is.
 
View State  

View State is the method to preserve the Value of the Page and Controls between round trips. It is a Page-Level State Management technique. View State is turned on by default and normally serializes the data in every control on the page regardless of whether it is actually used  during a post-back. 
 
Now I am showing you an examle of what the problem is when we don't use view state.
 
Step 1

Open Visual Studio 2010.



Step 2

Then click on "New Project" > "Web" >"ASP.NET Empty Web Application".

Step 3

Now click on Solution Explorer.


 
Step 4

Now right-click on the "ADD" > "New Item" > "Web Form" and add the name of the Web Form just like I did in WebForm6.aspx.


 
 Step 5

After adding the WebForm6.aspx you will see the following code:

  1. <%@ page language="C#" autoeventwireup="true" codebehind="WebForm6.aspx.cs" inherits="view_state.WebForm6" %>  
  2.    
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.         User Name:-<asp:textbox id="TextBox1" runat="server"></asp:textbox>  
  12.         <br />  
  13.         Password  :-<asp:textbox id="TextBox2" runat="server"></asp:textbox>  
  14.         <br />  
  15.         <asp:button id="Button1" runat="server" onclick="Button1_Click" text="Submit" />  
  16.         <asp:button id="Button3" runat="server" onclick="Button3_Click" text="Restore" />  
  17.     </div>  
  18.     </form>  
  19. </body>  
  20. </html>  

Code

Now write the code as in the following:

  1. //Declaration of a and b  
  2. public string a, b;  
  3. protected void Button1_Click(object sender, EventArgs e)  
  4. {  
  5.     //TextBox1 and TextBox2 Value is Assigning on the variable a and b  
  6.     a = TextBox1.Text;  
  7.     b = TextBox2.Text;  
  8.     //after clicking on Button TextBox value Will be Cleared  
  9.     TextBox1.Text = TextBox2.Text = string.Empty;  
  10. }  
  11.    
  12. protected void Button3_Click(object sender, EventArgs e)  
  13. {  
  14.     //value of variable a and b is assingning on TextBox1 and Textbox2  
  15.     TextBox1.Text = a;  
  16.     TextBox2.Text = b;  
  17. }   

Output

Now the output is:


 
It only happens because all the controls are classes and on the server all the Control Objects are created and then after the round trip the Page is returned to the client's browser in HTML format and the objects are destroyed at the server.
 
After the Submit button is clicked the value of user name and password is submited to the server. We cannot restore the value again because after the postback the instance of the control is destroyed and on clicking of the Restore Button the server takes a new request and the server cannot restore the value of the TextBox.
 
Features Of View State

These are the main features of view state:

  1. Retains the value of the Control after post-back without using a session.
  2. Stores the value of Pages and Control Properties defined in the page.
  3. Creates a custom View State Provider that lets you store View State Information in a SQL Server Database or in another data store.

And now I am explaining the stored value in the View State and the remaining steps are the same as the previous.
 
Code

Now write this code,

  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     //Value of Textbox1 and TectBox2 is assigin on the ViewState  
  4.     ViewState["name"] = TextBox1.Text;  
  5.     ViewState["password"] = TextBox2.Text;  
  6.     //after clicking on Button TextBox value Will be Cleared  
  7.     TextBox1.Text = TextBox2.Text = string.Empty;  
  8. }  
  9. protected void Button3_Click(object sender, EventArgs e)  
  10. {  
  11.     //If ViewState Value is not Null then Value of View State is Assign to TextBox  
  12.     if (ViewState["name"] != null)  
  13.     {  
  14.         TextBox1.Text = ViewState["name"].ToString();  
  15.     }  
  16.     if (ViewState["password"] != null)  
  17.     {  
  18.          TextBox2.Text = ViewState["password"].ToString();  
  19.     }  
  20. }    

Output

Now the output is,


 
After clicking on the Submit Button the value of user name and password is submitted in View State and the View State stores the value of user name and password during post-back.

After click on the Restore Button we can get the value again. The Value must be retained during post-back and the values are stored into a base 64 encoded string and this information is then put into the View State Hidden Field.
 
Data Objects That Can be Stored in View state

  1. String
  2. Boolean Value
  3. Array Object
  4. Array List Object
  5. Hash Table 
  6. Custom type Converters

Advantages of View State

  1. Easy to Implement.
  2. No server resources are required: The View State is contained in a structure within the page load.
  3. Enhanced security features: It can be encoded and compressed or Unicode implementation.

Disadvantages of View State

  1. Security Risk: The Information of View State can be seen in the page output source directly. You can manually encrypt and decrypt the contents of a Hidden Field, but It requires extra coding. If security is a concern then consider using a Server-Based state Mechanism so that no sensitive information is sent to the client.
  2. Performance: Performance is not good if we use a large amount of data because View State is stored in the page itself and storing a large value can cause the page to be slow.
  3. Device limitation : Mobile Devices might not have the memory capacity to store a large amount of View State data.
  4. It can store values for the same page only.

When We Should Use View State

  1. When the data to be stored is small.
  2. Try to avoid secure data.

How to Enable and Disable View State

You can enable and disable View State for a single control as well as at the page level also. To turn off View State for a single control, set the EnableViewState property of that control to false. 

  1. TextBox1.EnableViewState=false;   
To turn off the View State for an entire page, we need to set EnableViewState to false of the page directive as shown below:
  1. <%Page Language="C#" EnableViewState="false";  
For enabling the same, you need to use the same property just set it to "True".
 
View State Security

View State Data is stored in the form of Base 64 encoding but it is not more secure, anyone can easily break it. So there are the following 2 options, 
  1. Using the MAC for Computing the View State Hash Value

    Generally, the larger MAC key is used to generate a Hash Key. When the key is auto-generated then ASP.NET uses SHA-1 encoding to create a larger key. Those keys must be the same for all the server. If the key is not the same and the page is posted back to a different server than the one that created the page then the ASP.NET Page Framework raises an exception. We can enable it by using,
    1. <%Page Language="C#" EnableViewState="true"  EnableViewStateMac="true";   
  2. Encryption
     
    By using MAC Encoding we cannot prevent the viewing of the data so to prevent the viewing, transmit the page over SSL and encrypt the View State Data. To encrypt the data we have the ViewStateEncryptionMode Property and it has the following 3 options:
     
    • Always: Encrypt the data Always.
    • Never: Encrypt the data Never.
    • Auto: Encrypt if  any Control request specially for Encryption

We can enable it by using,

  1. <%Page Language="C#" EnableViewState="true ViewStateEncryptionMode="Always" 

 

Up Next
    Ebook Download
    View all
    Learn
    View all