ASP.Net MVC Scribblings
  • Introduction
  • Introduction
    • My ASP.net MVC Scribblings
    • Test
  • ASP.net MVC
    • Routing
    • Passing Data in MVC
      • ViewData and ViewBag
      • ViewData / ViewBag
      • TempData
      • Session Variables
    • ModelBinder
    • Advantages of MVC over WebForms
    • Data Annotation
    • RAZOR
    • ActionName decorator for overloaded Controller actions
    • Security
      • CSRF
      • XSS
    • Shared Layout page
    • Custom Claims-based Windows Authentication in ASP.net MVC 5
Powered by GitBook
On this page

Was this helpful?

  1. ASP.net MVC
  2. Passing Data in MVC

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>
PreviousTempDataNextModelBinder

Last updated 5 years ago

Was this helpful?