In this article I will explain a short tutorial with example on how to use Session in ASP.Net MVC Razor.
Session is derived from the HttpSessionStateBase class and is used for persisting data i.e. State Management across requests in ASP.Net MVC Razor.
 
 
What is Session
1. Session saves data similar to a Dictionary object i.e. Keys and Values where Keys are String while Values will be objects.
2. Data is stored as Object in Session.
3. While retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving.
4. Session is used for passing value from Controller to View and also from one Controller to another.
5. Session is available across multiple requests. It is not destroyed on redirection.
 
 
Session Example
In the below example, a string value is set in the Session object in Controller and it is then displayed in View.
Controller
public class FirstController : Controller
{
    // GET: First
    public ActionResult Index()
    {
        Session["Message"] = "Hello MVC!";
        return View();
    }
}
 
View
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @Session["Message"]
    </div>
</body>
</html>
 
 
Screenshot
ASP.Net MVC: Session Tutorial with example
 
 
Downloads