For instance, if you had a login page which has 2 textboxes, one for the name and the other for the password. When you click the Login button on that page, the application needs to ensure that the username and password get passed onto the next page. In ASP.Net, this is done in a variety of ways. The first way is via a concept called ViewState. This is wherein ASP.Net automatically stores the contents of all the controls. It also ensures this is passed onto the next page. This is done via a property called the ViewState. It is not ideal for a developer to change anything in the view state. This is because it should be handled by ASP.Net only. The other way is to use an object called a “Session Object.” The Session object is available throughout the lifecycle of the application. You can store any number of key-value pairs in the Session object. So on any page, you can store a value in the Session object via the below line of code. Session[“Key”]=value This stores the value in a Session object and the ‘key’ part is used to give the value a name. This allows the value to be retrieved at a later point in time. To retrieve a value, you can simply issue the below statement. Session[“Key”] In our example, we are going to use the Session object to store the name entered in the name textbox field in the page. We are then going to retrieve that value and display it on the page accordingly. Let’s add the below code to the Demo.aspx.cs file.

Code Explanation:-

The first line of code takes the value of the Name textbox control and stores it in the Session object. By specifying the code of Session[“Name”] , we are giving the property a name called “Name.” By specifying a name for the property, it becomes easier to retrieve it at a later point in time. The next line of code retrieves the stored value from the Session object. It then writes this value via the ‘Response.Write’ method back to the client. Finally, we make all the controls on the form as invisible. If we don’t do this, all the controls plus our response values will be displayed together.

Once you make the above changes, you will see the following output Output:

From the output, you can see that the Session value of name was retrieved and displayed in the browser. Summary:

Session management is a way in ASP.net to ensure that information is passed over from one page to the other. The view state property of a page is used to automatically pass the information of controls from one page to the other. The ‘Session’ object is used to store and retrieve specific values within a web page.