Search code examples
asp.net-mvcsessionasp.net-mvc-4session-variables

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


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.


Solution

  • 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;