In this article, I’m trying to explain the concept of session in asp.net
As we all know, HTTP is a stateless protocol, it
can't hold client information on a page. If the user inserts some information
and move to the next page, that data will be lost and the user would not be able
to retrieve that information. Session provides a facility to store information
on server memory. It can support any type of object to store along with our own
custom objects. For every client, session data is stored separately, which means
session data is stored on a per client basis.
ASP.NET session state enables you to store and retrieve values for a user as the
user navigates ASP.NET pages in a Web application. ASP.NET session state
identifies requests from the same browser during a limited time window as a
session, and provides a way to persist variable values for the duration of that
session.
Advantages of Session:-
- It helps maintain user state and data all over the application.
- It is easy to implement and we can store any kind of object.
- Stores client data separately.
- Session is secure and transparent from the user.
Example:-
Step 1:-
Design the form as shown below:-
Step 2:-
Write the code in the webform1.aspx.cs
|
using
System;
namespace
SessionWebApplication
{
public
partial
class
WebForm1 :
System.Web.UI.Page
{
protected void
Page_Load(object sender,
EventArgs e)
{
}
protected void
btnSave_Click(object sender,
EventArgs e)
{
//storing
data in Session variable name and city
Session["Name"] = txtName.Text;
Session["City"] = txtCity.Text;
txtName.Text =
"";
txtCity.Text =
"";
lblMsg.Text =
"Data saved in session";
}
}
}
|
Step 3:-
Webform2.aspx
|
<div>
<asp:Label
ID="lblName" runat="server"></asp:Label>
<br/>
<asp:Label
ID="lblCity" runat="server"></asp:Label>
<br/>
<br />
<asp:HyperLink
ID="HyperLink1"
runat="server" NavigateUrl="~/WebForm1.aspx">Back</asp:HyperLink>
</div>
|
Step 4:-
Write code in webform2.aspx.cs
|
using
System;
namespace
SessionWebApplication
{
public
partial
class
WebForm2 :
System.Web.UI.Page
{
protected void
Page_Load(object sender,
EventArgs e)
{
//retrieving
data from session variable name and city
lblName.Text =
"Hi " + Session["Name"].ToString();
lblCity.Text =
"You live in " + Session["City"].ToString();
}
}
}
|
Step 5:-
Run the application
After filling values in the textboxes click on the save to session button
You will get a message that data saved in session and then click on Test Session
No comments:
Post a Comment