Session variable in MVC

by Sachin Singh


Posted on Tuesday, 07 April 2020

Tags: How to use session in mvc.

Session:-

Session generally means a time period for something, for example when you logged in to Facebook, a new session starts and you don't need to log in again to access other pages of your application, but after logout, you need to again login to access the pages, this is because the session ends. Keeping this in mind we have a Session variable in Asp.Net where we generally store user's information and destroy the session when the user logs out. Although we could store anything in a session, it is more suitable to store user-related information because it is for what it has invented.

 1. Session saves the data in the same way as any other dictionary object does that is in the key-value pair. where Key is string and value is object.

 2. As it stores the value as an object, so Typecasting is necessary while retrieving the value.

 3. Also, it is recommended to do a null check before retrieving the value from the session to avoid a null exception.

 4. A session can be used to pass data from Controller to View or from Controller to Controller.

 5. The session is available throughout the application and does not destroy across multiple requests. In short, it can be used anywhere in the application until the session ends.

Let's understand it with an example.

Let's create two controllers and two Action Method, one Action Method for each controller. And Set the session value in the Action Method of the first controller and use it in the second controller's Action Method.


    public class FirtsController: Controller
    {
        //
        // GET: /Firts/
        public ActionResult Index()
        {
            Session["Data"] = "Hello user welcome";
            return View();
        }
	}

    public class SecondController : Controller
    {
        //
        // GET: /Second/
        public ActionResult Index()
        {
            return View();
        }
	}


   @{
    ViewBag.Title = "Index";
     }

   <h2>First Controller's Index</h2>
     @Session["Data"]

     <a href="/Second/Index">Go to second controller</a>


    @{
    ViewBag.Title = "Index";
      }

   <h2>second contrller's Index</h2>
   @Session["Data"]

Now ,Run the index of FirstController.You will get below result.

First controller's Index View
First Controller's Index view
Now,click the go to second controller ,you will get the below result.
First controller's Index View
Second Controller's Index View

So, It can be concluded, that the session persists the value across multiple requests and can be used across the whole project. As a session represents a user session,it is recommended to use session only to store user related data