Monday, February 25, 2008

Using the Session Object

Session is the time period during which a user interacts with a particular web application / webpage. Session object is an object which maintains this information specific to the particular visitor, internally. A session and hence the information that it carries can end deliberately through the code or on a timeout. Some of the alternatives using session object is the use of query string and hidden fields. However if you need to do complex manipulation of state data then the Session object is the way to go.

Initiating a Session


string uname = "Firstname Lastname";
Session.Add("userName",uname);


The above line of code stores the value of uname in a session variable called userName. Now this session variable is carried automatically across pages on the website and hence can accessed anywhere you need.

Accessing the Session object

Lets say you need to place this userName in some page where the string uname is not accessible anymore (thats the reason we created the session object in this case!)


Label mylabel = new Label();
mylabel.text = (string)Session["userName"];


As can be noted the session object is cast as a string else the left hand side would be a string and the right hand side would be an object and hence you would get the error
"you can't assign an Object to a String"

Modifying the Session variable

Suppose at some point of time you need to put a different value into a session variable. This can be done in the following way.


Session["userName"] = "My New value here";


Lifetime of a Session

The timeout period of a session object can be found by using

Session.Timeout.ToString();


The default value for this is usually 20 minutes which can be changed depending on the needs of the particular application.
Session.Timeout = 30

will make change it to 30 minutes.

Deleting a Session variable

Session.Remove("userName");


Session variables are a convenient way of storing and accessing data over multiple pages. However, very huge data should not be stored in session variables as it causes load on the server resources.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home