Click here to Skip to main content
Click here to Skip to main content

Beginner's Guide To View State

By , 29 Nov 2008
 
Prize winner in Competition "Best ASP.NET article of November 2008"

Table of Contents

Introduction

First of all I want to thank Sean Ewington for his great initiative to write Beginner's Walk for Web Development article. I have decided to write some articles on state management There are a few article on Code project on State Management, basically on Session, Caching, Cookies, etc. Though all are very good article, still I have planned for write some article on state management. and I believe that should definitely helps to all the Beginners. And I have organized the content in a way that it would be helpful to not only beginners also to advance user also.

In this article, I will cover the fundamentals of State Management and Details of View State.

What is state management?

Web is Stateless. It means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, its can't holds the client information on page. As for example , if we enter a text and client on submit button, text does not appear after post back , only because of page is recreated on its round trip.

User_S9_1.JPG

As given in above pages, page is recreated before its comes to clients and happened for each and every request. So it is a big issue to maintain the state of the page and information for a web application. That is the reason to start concept of State Management. To overcome this problem ASP.NET 2.0 Provides some features like View State, Cookies, Session, Application objects etc. to manage the state of page.

There are some few selection criteria to selected proper way to maintain the state, as there are many way to do that. Those criteria are:

  • How much information do you need to store?
  • Does the client accept persistent or in-memory cookies?
  • Do you want to store the information on the client or on the server?
  • Is the information sensitive?
  • What performance and bandwidth criteria do you have for your application?
  • What are the capabilities of the browsers and devices that you are targeting?
  • Do you need to store information per user?
  • How long do you need to store the information?
  • Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that serves the application?

So, when ever you start to think about state management, you should think about above criteria. based on that you can choose the best approaches for manages state for your web application.

Different types of state management?

There are two different types of state management:

  1. Client Side State Management
    • View State
    • Hidden Field
    • Cookies
    • Control State
  2. Server Side State Management
    • Session
    • Application Object
    • Caching
    • Database

Client Side state management does not use any server resource , it store information using client side option. Server Side state management use server side resource for store data. Selection of client side and server side state management should be based on your requirements and the selection criteria that are already given.

What is view state?

View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.

Example:

If you want to add one variable in View State,

 ViewState["Var"]=Count;

For Retrieving information from View State

string Test=ViewState["TestVal"];

Sometimes you may need to typecast ViewState Value to retreive. As I give an Example to strore and retreive object in view state  in the last of  this article.

Advantages of view state?

This are the main advantage of using View State:

  • Easy to implement
  • No server resources are required
  • Enhanced security features ,like it can be encoded and compressed.

Disadvantages of view state?

This are the main disadvantages of using View State:

  • It can be performance overhead if we are going to store larger amount of data , because it is associated with page only.
  • Its stored in a hidden filed in hashed format (which I have discussed later) still it can be easily trapped.
  • It does not have any support on mobile devices.

When we should use view state?

I already describe the criteria of selecting State management. A few point you should remember when you select view state for maintain your page state.

  • Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
  • Try to avoid storing secure data in view state

WhenViewState.PNG

When we should avoid view state?

You won't need view state for a control for following cases,

  • The control never change
  • The control is repopulated on every postback
  • The control is an input control and it changes only of user actions.

Where is view state stored?

View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hidden field to store its information in a encoding format.

Suppose you have written a simple code , to store a value of control:

ViewState["Value"] = MyControl.Text;

Now, Run you application, In Browser, RighClick > View Source , You will get the following section of code

User_S1.jpg

Fig : View state stored in hidden field

Now , look at the value. looks likes a encrypted string, This is Base64 Encoded string, this is not a encoded string. So it can easily be decoded. Base64 makes a string suitable for HTTP transfer plus it makes it a little hard to read . Read More about Base64 Encoding . Any body can decode that string and read the original value. so be careful about that. There is a security lack of view state.

How to store object in view state?

We can store an object easily as we can store string or integer type variable. But what we need ? we need to convert it into stream of byte. because as I already said , view state store information in hidden filed in the page. So we need to use Serialization. If object which we are trying to store in view state ,are not serializable , then we will get a error message .

Just take as example,

//Create a simple class and make it as Serializable
[Serializable]
public class student
{
    public int Roll;
    public string Name;
    public void AddStudent(int intRoll,int strName)
      {
        this.Roll=intRoll;
        this.Name=strName;
           }
}

Now we will try to store object of "Student" Class in a view state.

 //Store Student Class in View State
student _objStudent = new student();
_objStudent.AddStudent(2, "Abhijit");
ViewState["StudentObject"] = _objStudent;

//Retrieve Student information view state
 student _objStudent;
_objStudent = (student)ViewState["StudentObject"]; 

How to trace your view state information?

If you want to trace your view state information, by just enable "Trace" option of Page Directive

User_S2.gif

Now Run your web application, You can view the details of View State Size along with control ID in Control Tree Section. Don't worry about "Render Size Byte" , this only the size of rendered control.

User_S3.jpg

Fig : View State Details

Enabling and Disabling View State

You can enable and disable View state for a single control as well as at page level also. To turnoff view state for a single control , set EnableViewState Property of that control to false. e.g.:

TextBox1.EnableViewState =false;

To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.

User_S4.gif

Even you disable view state for the entire page , you will see the hidden view state tag with a small amount of information, ASP.NET always store the controls hierarchy for the page at minimum , even if view state is disabled.

For enabling the same, you have to use the same property just set them as True

as for example, for a single control we can enabled view state in following way,

TextBox1.EnableViewState =true;

and for a page level,

User_S5.gif

How to make view state secure?

As I already discuss View state information is stored in a hidden filed in a form of Base64 Encoding String, and it looks like:

User_S1.jpg

Fig : View state stored in hidden field

Many of ASP.NET Programmers assume that this is an Encrypted format, but I am saying it again, that this is not a encrypted string. It can be break easily. To make your view state secure, There are two option for that,

  • First, you can make sure that the view state information is tamper-proof by using "hash code". You can do this by adding "EnableViewStateMAC=true" with your page directive. MAC Stands for "Message Authentication Code"

User_S6.gif

A hash code , is a cryptographically strong checksum, which is calculated by ASP.NET and its added with the view state content and stored in hidden filed. At the time of next post back, the checksum data again verified , if there are some mismatch, Post back will be rejected. we can set this property to web.config file also.

  • Second option is to set ViewStateEncryptionMode="Always" with your page directives, which will encrypt the view state data. You can add this in following way

User_S7.gif

It ViewStateEncryptionMode has three different options to set:

  • Always
  • Auto
  • Never

Always, mean encrypt the view state always, Never means, Never encrypt the view state data and Auto Says , encrypt if any control request specially for encryption. For auto , control must call Page.RegisterRequiresViewStateEncryption() method for request encryption.

we can set the Setting for "EnableViewStateMAC" and ViewStateEncryptionMode" in web.config also.

User_S8.gif

Note : Try to avoid View State Encryption if not necessary , because it cause the performance issue.

Some Important Points

Questions Answer
Client Side or Server Side ? Client Side
Use Server Resource ? No
Easy to implement ? Yes
Cause Performance Issue ? For heavy data and case of encryption & decryption
Support Encryption Decryption? Yes
Can store objects ? Yes, but you need to serialize the class.
Timeout No

That's all for view state. Hope you have enjoyed this article, please don't forget to give me your valuable suggestions. If anything need to update or changed please post your comments and please give me suggestion.

Reference

History

Written on Saturday, 29th November, 2008

Small Correction on Monday December 2008

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Abhijit Jana
Software Developer (Senior)
India India
.NET Consultant | Former Microsoft MVP - ASP.NET | CodeProject MVP, Mentor, Insiders| Technology Evangelist | Author | Speaker | Geek | Blogger | Husband
 
Blog : http://abhijitjana.net
Web Site : http://dailydotnettips.com
Twitter : @AbhijitJana
My Kinect Book : Kinect for Windows SDK Programming Guide
Follow on   Twitter

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberMember 97897296-Jun-13 4:49 
thanks a lot.
QuestionCommentmembertarun _sharma14-Apr-13 20:12 
Superb Article dude..u Rocks!!
GeneralMy vote of 5memberMember 83913762-Apr-13 2:47 
Really awesome article on ViewState at one place with concise solution.
 
Thx,
-Rajan
GeneralMy vote of 5memberabhi3eee1-Apr-13 19:02 
Nice Article
GeneralMy vote of 5memberabhi99314-Mar-13 7:20 
This is called knowledge
QuestionGood articlememberSampath Sridhar7-Mar-13 16:34 
Thanks for the article.
Able to get good understanding of Viewstate through this one.
GeneralYou made Viewstate very simplememberAbhinesh M24-Feb-13 23:17 
The article was very easy to understand and implement viewstate. Thanks.
GeneralMy vote of 4memberMukesh_B22-Feb-13 4:03 
Very well written
GeneralMy vote of 5memberUday P.Singh17-Feb-13 7:37 
Very nice
GeneralNice Articlemembervinay raghavendr3-Feb-13 20:40 
Article is very good, good explanation with example. I look forward of articles on remaining types of state management.
GeneralMy vote of 5memberZPop26-Jan-13 0:04 
Excellent. Thanks
GeneralMy vote of 5memberravikant.sharma0123-Jan-13 3:29 
great article and very easy and it made the view state my cup of tea
GeneralMy vote of 5memberchaitanyasingh12-Jan-13 5:03 
good article for beiginners
Questionfield and propertiesmemberrajyash8-Jan-13 22:45 
What is difference bet field and properties in asp.net
QuestionView Statememberrajyash8-Jan-13 22:43 
Excellent tutorials
GeneralView StatememberMember 81642773-Jan-13 20:38 
Excellent Explanation
Questionhow to clear the viewstate object?memberbluesathish19-Dec-12 19:08 
hi Abhijit Jana,
thanks for your nice article. And i've the doubt that how we can clear (or) dispose the viewstate objects. Since its uses client side resources, we need to clear (or) dispose it when it is not in use. kindly share your suggestion for this.
 
Regards,
Bluesathish
GeneralCommentmemberAbhijit Parab16-Dec-12 22:10 
Excellent article to understand the concept of View State Smile | :)
GeneralMy vote of 5memberSwathi Nagaraj5-Nov-12 19:23 
Its easily understable
Questionmy vote for 4membergirishmeena24-Oct-12 4:35 
it is good article written by you.
GeneralMy vote of 4memberanilsarapati28-Sep-12 16:16 
It is good for starting learners....
GeneralMy vote of 4membernagpalvikas27-Sep-12 3:25 
Adding a scenario would have added cherry to the cake. It would have made the article even more interesting if you would have given a scenario where View state is beneficial.
QuestionAbout an articlememberrahul75964-Sep-12 8:37 
excellent Article It is really helpful.but please tell me where can i found your other articles of state management?
GeneralMy vote of 4memberS.K.Tripathi30-Aug-12 4:20 
good one...
GeneralMy vote of 4memberusrikanthvarma12-Aug-12 21:25 
Very good Article....
GeneralMy vote of 5memberMember 933491112-Aug-12 20:44 
very good understanding is possible... great work
GeneralThankqmemberjareenkumar26-Jul-12 20:18 
Its an very good article,i liked it very much and its very informative Laugh | :laugh: Smile | :)
QuestionThanks AbhijitmemberGaurang Naik27-Jun-12 20:57 
Very nice and brief yet simple to understand. Thanks yaar.
GeneralMy vote of 4memberGaurang Naik27-Jun-12 20:55 
Fantastic for a beginer!
GeneralGot a Good help from this1 :)memberkiransolkar19-Jun-12 0:41 
Nice Article
GeneralMy vote of 4memberAnanth Rao Poolla4-Jun-12 21:25 
Good to know from scratch
GeneralMy vote of 5membernikhil _singh15-May-12 1:16 
awesome article to understand ViewState from Scratch.
GeneralMy vote of 3memberChamila Ranasinghe10-May-12 18:09 
Short & Sweet
GeneralGood ArticlememberAlireza_13627-May-12 6:08 
Many Thanks
GeneralMy vote of 5memberbaihualin198331-Mar-12 22:10 
Excellent Article.
Questionviewstate scopememberMuraliKrishna120412-Mar-12 4:33 
What is the scope of the viewstate information.i mean when it expires?
GeneralMy vote of 5memberSupriya Srivastav24-Jan-12 21:00 
Excellent Article.
GeneralMy vote of 4memberRiyasktr23-Dec-11 9:57 
For beginners it's nice topic
GeneralMy vote of 5memberPrince Antony G29-Nov-11 22:16 
nice
GeneralMy vote of 5memberShanmugam R P25-Oct-11 7:14 
Excellent article
GeneralMy vote of 5memberfcis20102-Sep-11 10:38 
Very good
GeneralNice articlememberquanvt5-Jun-11 22:05 
Simple and good article about viewstate. Thank for sharing.
GeneralMy vote of 5memberam.net12-Apr-11 20:55 
nice and clear artical.
GeneralThanks a lot for wonderfull article to begin in view statememberchandru201128-Mar-11 3:03 
i'm a new to c# i just admired the way of you explains it gives me lot , i'm going to practice , if find any difficulty i let u know please help me
 
thanks a lot
chandru.v

GeneralMy vote of 5memberchandru201128-Mar-11 3:00 
clear cut example for begginners
GeneralMy vote of 5memberThat's Aragon21-Mar-11 4:15 
Worth reading it. Get good knowledge. Smile | :) Thanks.
GeneralMy vote of 5membermanikanta51810-Mar-11 19:18 
This is the greate artical....you are greate person man...cool....
GeneralMy vote of 5memberVishnuSharmila26-Jan-11 13:44 
Excellent and easy to understand
GeneralMy Vote for 5memberMansi201026-Dec-10 23:34 
Simple and Good Article
GeneralRe: My Vote for 5mvpAbhijit Jana10-Jan-11 12:22 
Thanks !!Thumbs Up | :thumbsup:
Cheers !
Abhijit Jana | My Blog | @Twitter | Daily .Net Tips


General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130617.1 | Last Updated 29 Nov 2008
Article Copyright 2008 by Abhijit Jana
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid