In this article I will explain with an example, how to use Session in ASP.Net MVC.
Session is derived from the HttpSessionStateBase class and is used for persisting data i.e. State Management across requests in ASP.Net MVC.
 
 
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.
 
 
Controller
The controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, a string value is set in the Session object and finally, the View is returned.
public class FirstController : Controller
{
    // GET: First
    public ActionResult Index()
    {
        Session["Message"] = "Hello MVC!";
        return View();
    }
}
 
 
View
Inside the View, the Session variable is displayed using Razor syntax.
@{
    Layout = null;
}
 
<!DOCTYPE
<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