Viewstate and Session

Posted on: Wed Aug 13 11:35:31 -0700 2008. Updated on: Wed Aug 13 11:36:38 -0700 2008.
Category: .NET C#

When needing to store data for use in a different postback we can use either a session or viewstate key.
The Session object is kept on the server and can be used in different pages. So if you need an object that will always be available no matter where in your web application the user is, you should use the Session.
The Viewstate is kept on the client, and is actually encoded into the html page that is spit out to the client. It is only available in the page that it was defined. You can postback to the same page and have access to the defined viewstate but if the user goes to a different page and comes back, the viewstate will be gone.

Using a Session:
// setting it
int number = 25;
Session["key1"] = number;
// retrieving
int num2 = (int)Session["key1"];
// note how you must type cast it to get it out correctly

// you can also put in any serializable object, ie a datatable.
DataSetClients.ClientsTable table = WebService.GetClients();
Session["key2"] = table;
// to retrieve simply cast it
table = (DataSetClients.ClientsTable)Session["key2"];

// check if Session is defined and exists
if(Session["key1"] == null)
{
    // not defined
}

You can interchange the above for ViewState["key3"] and get the same result.

Comments:

Add a Comment:

simple_captcha.jpg
(human authentication)


Ads

Categories

About

Random foliage

This website is meant to be a reference for ASP Dot Net developers. The entries are a compilation of things I've figured out how to do and that I deem useful to keep of track for future reference. Assumptions: web development with: C Sharp (vb sucks), visual studio 05/08, .net 3.5, meant for programmers. Written by: James Reategui.