Session
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.
- <table>
- <tr>
- <td>
- Name
- </td>
- <td>
- <asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
- </td>
- <td>
- <asp:Button ID="BtnRedirect" runat="server" Text="Submit" OnClick="BtnRedirect_Click" />
- </td>
- </tr>
-
- </table>
Add another Web form. Name it “Form2.aspx”. Write the following HTML code in it.
- <asp:Label ID="LblName" runat="server"></asp:Label>
In Form1.aspx.cs write the below code on button click.
- protected void BtnRedirect_Click(object sender, EventArgs e)
- {
- Session["UserName"] = TxtName.Text;
- Response.Redirect("Form2.aspx");
- }
In the Form2.aspx.cs page load write the following code.
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- if (Session["UserName"] != null)
- {
- LblName.Text = Convert.ToString(Session["UserName"]);
- }
- else
- {
- LblName.Text = "Guest User!!";
- }
- }
- }
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.