Thursday, 12 January 2012

ASP.Net C# session object


How to pass values to a session (ASP.net C#)

When working on ASP.net web pages or any other web programming for that matter, there comes a point we need to pass values or objects between web pages.
There are several ways of doing this, as examples
We can use the view state string that passes values as a string in the page or
We can use a cookie which is not more than a text file that stores data in the client side computer or
We can use a session variable.

In this tutorial we look at how to work with a session variable
All you have to do is, create a session variable, pass the values in to it and retrieve when necessary.

So here’s the way to do it :D




Creation of a session

Suppose there is an integer variable and you want to assign it to the session object.

//integer variable
int intVar = 10;

//below the int variable is assigned to the session
//remember you can even add an object to a session
//the <userID> is the session variable name and it is written within double quotes and it’s the name
//access the session object
Session[“userID”] = intVar;




Accessing the session variable

To check this, you should go to another page or some where
And in the code behind we can assess the variable using the following code.

Make sure you get the code working inside a page load method or something like that

//remember you have to cast it to an int type.
//if you passed another object, as an example a User type object, then cast it to User type

int passedVariable  = (int)Session[“userID”];




As an example of the usage of this ( in my opinion) we can create a session object in the log in page and pass it to the master page if we need to change the master page according to the authentication level and every time we need to check for authentication or authentication level, in every page load, check the session variable and see if its null or not.
If you want to log out set the session as null.

(Please note that this is one of the ways of doing it and it might not be the best way, if you have any better way of working with sessions or log ins please be kind enough to share them with me)

Hope that helps
Cheers

No comments:

Post a Comment