Intro to Sessions in ASP.Net

Learning how sessions work in ASP.NET 4.0 is fundamental for any beginner developing websites. This is especially true if the site’s functionality relies on retrieving user-related information on any page as the user visits the website. This article will explain what sessions are, and illustrate them with complete code examples.

Sessions are used to pass the value from one page to another with no effort from the user. With a session, if the user inputs values on the original page and you need to access them on another page, you can retrieve the values stored in the session without making the user submit those values again. Sessions are important to any user-related authentication (if you’re using the https protocol), user-related validation and customization of visitor experiences in your website.

This tutorial will use Visual Basic to illustrate ASP.NET sessions, though the code can be converted to equivalent C# code. A complete project can be downloaded at the end of this tutorial.

Getting Started: Learning with an Example

The best way to teach sessions to you is to illustrate the concept with code examples. Suppose you are designing a website with only two ASPX pages. The first page is the original page, and the other page is the auxiliary page. The user is required to input data only on the original page. You will access this data on the second page without requiring the user to enter the data again. In this example, you will need sessions to pass these values from the original page to another page.

There will be buttons on the page that the user can click to add new values to the session, view the stored values in the session and empty/clear the session.

The flowchart of implementation is as follows:

Creating Visual Web Developer Project and Default.aspx

Let’s start creating the ASP.NET 4.0 website project.

1. Launch Microsoft Visual Web Developer 2010 Express. This IDE is the development environment for ASP.NET 4.0.

2. Go to File –> New Web Site

3. Select ASP.NET Empty Web Site.

4. Under “Web Location,” select “File System” and choose the path on which you would like to save the project in your website. Indicate the project name, “ASPNETsession,” in the path. For example:

L:aspdotnetprojectsdotnetversion4ASPNETsession

Click OK.

5. Go into Visual Web Developer and go to Add New Item.

6. Under Installed Templates – select “Visual Basic” and “Web Form.” Make sure to click “Place code in separate file.”

7. Delete all of the code in Default.aspx, and replace it with the code below:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>This is the original page</title>
</head>
<body>
   
<form id="form1" runat="server">
<div>
Enter value that you would like to store into your current session.
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="This field cannot be blank" ControlToValidate="TextBox1" Font-Bold="True">       
</asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Add to Session State" Width="161px" />
<p>
<asp:Button ID="Button2" runat="server" Text="View Session State"    Width="160px" />
</p>
<asp:Button ID="Button3" runat="server" Text="Clear Session"       Width="160px" />
<br />      
<br />
<a href="Default2.aspx">Go to Another page</a>
<br />      
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>

This is how Default.aspx will look when launched in the browser:

How the Default.aspx Code Works

The code above consists of a text box that accepts user input that will be stored in the ASP.NET session state. The input will be validated to make sure that the user has not input empty values. Then there are three buttons to accomplish three session-related functions: adding values to the session’s state, viewing the session’s state, and clearing the session.

{mospagebreak title=More Visual Basic Code for Session}

Default.aspx.vb Visual Basic Code

In the Solution Explorer, double click Default.aspx.vb to access the VB.NET code. Remove all of the code and replace it with the code below:

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click

‘Check first if Default.aspx has been successfully validated client side

If Page.IsValid Then

‘Retrieve the inputted value from the text box

Dim data As String = TextBox1.Text

‘Store the retrieve data to the session variable MySession

Session("MySession") = data

‘Output the update session value back to the user browser

Label1.Text = "Session updated! Your session now contains <b>" + Session("MySession") + "</b>"

End If
End Sub

Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click

‘Check first if the session is empty or not
‘Then show content of the session if there are values stored.

If (Session("MySession") Is Nothing) Then
Label1.Text = "NOTHING, SESSION DATA LOST!"
Else
Label1.Text = "View session state output (data that is currently stored in the session): <b>" + Session("MySession") + "</b>"
End If
End Sub

Protected Sub Button3_Click(sender As Object, e As System.EventArgs) Handles Button3.Click

‘Clear Session using Session.Abandon()

Session.Abandon()
Label1.Text = "Your session is now cleared!"
End Sub
End Class

Add the second page: Default2.aspx

Add the second page by going to Website – Add New Item. Name the page as Default2.aspx. Add only two buttons for viewing the session state and clearing the sessions, refer to the code below:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>This is another page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button2" runat="server" Text="View Session State"
            Width="160px" />
<br />
<br />
<asp:Button ID="Button3" runat="server" Text="Clear Session"
            Width="160px" />
<br />      
<br />
<a href="Default.aspx">Back to original page</a>
<br />      
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label> 
</div>
</form>
</body>
</html>

This is how Default2.aspx would look in the browser:

Default2.aspx.vb Visual Basic Code

Double click Default2.aspx.vb, and then replace all of the code with the code below:

Partial Class Default2
Inherits System.Web.UI.Page

Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click

‘Check if there are values stored in the session

If (Session("MySession") Is Nothing) Then
            Label1.Text = "NOTHING, SESSION DATA LOST!"
Else
Label1.Text = "View session state output (data that is currently stored in the session): <b>" + Session("MySession") + "</b>"

End If
End Sub

Protected Sub Button3_Click(sender As Object, e As System.EventArgs) Handles Button3.Click

‘Clear Session

Session.Abandon()
Label1.Text = "Your session is now cleared!"
End Sub
End Class

Download and Learn How an ASP.NET Session Works

1. Download the complete project code here:

http://www.dotnetdevelopment.net/tutorials/ASPNETsession.zip

Extract the folder named as ASPNETsession.

2. Put the folder in your ASP.NET local project folder in your hard drive.

3. Launch Visual Web Developer Express 2010.

4. Open the project and double click on Default.aspx

5. Go to File –> View in Browser.

6. Try entering any text in the textbox. Suppose you enter the text “Codex M”

7. Click “Add to Session State.” You will then see confirmation text in the browser, implying that the value has been stored in the session.

Session updated! Your session now contains Codex M

8. Now click the link “Go to Another Page.” You will then go to another page, for example: http://localhost:50576/ASPNETsession/Default2.aspx

9. Let’s check to see if the ASP.NET session remembers the stored value. Click “View Session State.” There is a confirmation message showing the stored value in the session:

View session state output (data that is currently stored in the session): Codex M

10. Now try clearing the session by clicking the “Clear Session” button. You will read a confirmation message that the session is now cleared. Now try clicking “View Session State.” You will see a confirmation message: “NOTHING, SESSION DATA LOST!” This indicates that the session has now been cleared.

Although the example ASP.NET 4.0 project codes are simple, they provide good insight into how to set sessions, view sessions and clear them.

[gp-comments width="770" linklove="off" ]