ASP.NET MVC

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.

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago