Session Variables

Data in ViewData/ViewBag can be passed only from Controller to View

Data in TempData can be passed across the whole request from action to action ...to action to view.

But both ViewData and TempData don't preserve data between two requests of a session.

To preserve data between two requests of same session, use session variables:

public class HomeController: Controller{
 public ActionResult Index(){
     Session["MySessionData"] = "some session data"; // this data will preserved and available across sessions and actions
     return RedirectToAction("Home", "Home");
 }

 public ActionResult Home() {
     //Session["MySessionData"]  is available and hence can be used in Home view
     return View();
 }
}

Using TempData in View

<div>
    My data  I received from controller is: 
    @Session["MySessionData"]
</div>

Last updated

Was this helpful?