Posted on 4/7/2020 11:31:57 AM by Admin

Session variable in MVC

Session:-

 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 object ,so Type casting is necessary while retrieving the value.

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

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

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

Let's understand it with an example.

Lets create two Controller and two Action Method ,one for each controller. And Set the session value in Action Method of first controller and use it in 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

Clearly, the session persists the value across multiple request 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