How To Use Session In .NET MVC

Introduction

In ASP.NET, Session object is available in the ASP.NET lifecycle. We can store any kind of data as key-value pairs in the Session. We can use Session object anywhere in the application. Below is the syntax to store values in Session.

Session["KeyName"] = value;

This syntax will store the value inside Session which name is “KeyName”. This stored value to be retrieved anywhere in the application. Below is the syntax to retrieve a value from Session.

Session["KeyName"]

We can store anything in the session like a number, string, List<Object>, etc.

  • Store the List<Object> to a session
//To store
Session["items"] = _db.GetItems().ToList();

//To get which stored in a session
var items = Session["items"] as List<Item>;
  • Store a Number to a session
//To store
Session["age"] = 25;
 
//To get which stored in a session
var age = (int) Session["age"];

//Or
var age =  Convert.ToInt32(Session["age"]);

Here, is the example to save and retrieve values from the session.

public void Test()
{
  //set value
  Session["name"] = "Faisal Pathan";

  //get value
  var name = Session["name"]?.ToString();
}

If you want to learn how to remove a session or what is the difference between Session.Clear(), Session.Abandon() and Session.RemoveAll() you can read from here.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories