How to create a session variable in ASP.NET
Submitted by shantanu on Sat, 12/19/2009 - 13:38
Note: The reason this example uses two pages is to prove that a session variable is available to a second, third, fourth, etc. page in the web site. Request variables, which are an alternative to session variables, cannot be carried over from an ASP.NET Web Form on one page to a second page The first page must contain an ASP.NET Web Form that contains one <asp:textbox> server control and an <asp:button> server control. The "id" attribute of the textbox control should be set to "txtFirstName". The full code for the first page is provided below. Choose either C# or VB, depending on which language you've chosen for your ASP.NET site:
- Define an ASP.NET web site.
- Create two pages within the site. The first page will contain an ASP.NET Web Form that will post back to itself and then redirect to the second page.
This code pulls the contents from the <asp:textbox> server control named "txtFirstName" and creates a session variable named"sessFirstName" which is set equal to the contents of the server control. In other words, this code creates a session variable that holds the information the user enters on the form page. In the second page, access Code view by choosing View > Code, and enter the code below to write the session variable contents to the page. Again, choose either C# or VB, depending on which language you've chosen for your ASP.NET site: Session["sessFirstName"]='XYZ'; Save, publish and test both pages. If you do not get the expected results, check the capitalization and spelling of the server controls, session variable and request variable.
How to retrieve session Id in Asp.Net
Using session variables is very convenient and usually that is all you will need to maintain state from page to page. However, if you want to save the session state variable in a database for some reason to make sure something is visible only while a session is active (for instance if you want discussion posts to appear to the person posting as long as they are in their session but not to anyone else until you as the administrator approves the post). Here is the code to get the current SessionID.
public static string TheSessionId()
HttpSessionState ss = HttpContext.Current.Session;
HttpContext.Current.Session["test"] = "test";
Fountain Pen Guide Series, Session 1: Nibs, Feeds, and How They Come Together
How to Make a Login Form Using Session in ASP.Net C#
Session 1: Getting financial controls in place
Thigh Gap A Growing Obsession Online. But Not Necessarily At The Surgeon's Office
How Does Auto Repossession Process Work?