Session Management in ASP.NET


When a user connects to an ASP.NET website, a new session object is created. For every new request a new session variable is created. This session state object becomes part of the context and it is available throughout the application for a specific user.

Data can easily be transferred from one page to another.

Create a web application. Add a Web Form “Form1.aspx”. Write the following HTML code in it.

  1. <table>  
  2.         <tr>  
  3.             <td>  
  4.                 Name  
  5.             </td>  
  6.             <td>  
  7.                 <asp:TextBox ID="TxtName" runat="server"></asp:TextBox>  
  8.             </td>  
  9.             <td>  
  10.                 <asp:Button ID="BtnRedirect" runat="server" Text="Submit" OnClick="BtnRedirect_Click" />  
  11.             </td>  
  12.         </tr>  
  14.     </table>  
Add another Web form. Name it “Form2.aspx”. Write the following HTML code in it.
  1. <asp:Label ID="LblName" runat="server"></asp:Label>  
In Form1.aspx.cs write the below code on button click.
  1. protected void BtnRedirect_Click(object sender, EventArgs e)  
  2.         {  
  3.             Session["UserName"] = TxtName.Text;  
  4.             Response.Redirect("Form2.aspx");  
  5.         }  
In the Form2.aspx.cs page load write the following code.
  1. protected void Page_Load(object sender, EventArgs e)  
  2.    {  
  3.        if (!Page.IsPostBack)  
  4.        {  
  5.            if (Session["UserName"] != null)  
  6.            {  
  7.                LblName.Text = Convert.ToString(Session["UserName"]);  
  8.            }  
  9.            else  
  10.            {  
  11.                LblName.Text = "Guest User!!";  
  12.            }  
  13.        }  
  14.    }  
Let us now run the application. Set Form1.aspx as the start page.

Enter some text. Click on the Submit button.

We get the same name on the second page. Session is used to display the name here.

What if we jump to the Form2.aspx directly. In that case there will not be any session variable assigned and thus the else condition should work in that case. Let us run the Form2.aspx directly and see what happens.

So in this way we can use session in ASP.NET.