Just another tech site

ASP.NET Viewstate, Session, Application Variable


ViewState is a collection bag which holds key value pairs of changed control attributes. You can also utilize it to store your own values which will persist though a Page’s postbacks. ViewState is a member of Page, which means it is globably accessible throughout your Page. The ViewState is loaded early on in the Page creation (life cycle), and towards the end it is encrypted and outputed into the HTML. Therefore, when you add some data to the ViewState on the first page load, that data is being stored (encrypted) in the __ViewState hidden field you’ll find in the HTML source. When the page is loaded again (after you click the button), that value is decrypted and loaded into the ViewState bag, which means you’ll be able to access it.

In the codebehind of the Page or the WebUserControl place the code

private MyClass savedMyClass {
        get { return (MyClass)ViewState["savedMyClass"]; }
        set { ViewState["savedMyClass"] = value; }

In the generated HTML file you will find the following __ViewState hidden field


ASP.net by default mainstains a user’s session by a cookie.
Values that are stored into the Session variable are stored in the web server’s memory. As long as the user maintains their state, you can use the Session object as much as you want.

// When retrieving an object from session state, cast it to 
// the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;



This variable is stored in static members of the application class. This variable can be shared across user sessions. this variable is also stored at server side.


[1] http://msdn.microsoft.com/en-us/library/ms178581.aspx


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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

Tag Cloud

%d bloggers like this: