How to use sessions in an ASP.NET MVC 4 application?

Thuto Paul Gaotingwe picture Thuto Paul Gaotingwe · Jan 3, 2013 · Viewed 428.4k times · Source

I am new to ASP.NET MVC. I have used PHP before and it was easy to create a session and select user records based on the current session variables.

I have looked everywhere on the Internet for a simple step-by-step tutorial that can show me how to create and use sessions in my C# ASP.NET MVC 4 application. I want to create a session with user variables that I can access from anywhere in my controllers and be able to use the variables in my LINQ queries.

Answer

Jobert Enamno picture Jobert Enamno · Jan 3, 2013

Try

//adding data to session
//assuming the method below will return list of Products

var products=Db.GetProducts();

//Store the products to a session

Session["products"]=products;

//To get what you have stored to a session

var products=Session["products"] as List<Product>;

//to clear the session value

Session["products"]=null;