Sessions In MVC 4 - Part 2

Before reading this article, please go through the following article:

Let’s take one more step further in Session in MVC 4. Today, we will discuss about TempData. Hope readers remember about the following diagram.

mvc

TempData

TempData is used to share the data between controllers. TempData stays for a subsequent HTTP request.The value of TempData persists until it is read or until the current user’s session time out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request. TempData stores the data in Session object. But the object gets destroyed earlier than session.

An Example of TempData

Step 1: Create an empty MVC 4 Project.

Step 2: Right click on Modal, add new Modal name “Employee” and add the following code:

  1. public class Employee  
  2. {  
  3.     public string Name  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string EmpID  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string Designation   
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }  
Step 3: Add a “Home Controller” and add the following code in Index method:
  1. Employee objEmployee = newEmployee()   
  2. {  
  3.     Name = "Nishant",  
  4.         EmpID = "NM720501",  
  5.         Designation = "Technical Specialist"  
  6. };  
  7. TempData["Employee"] = objEmployee;  
  8. return RedirectToAction("EmployeeDetail");  
Create one more method name “EmployeeDetail” and add the following code:
  1. public ActionResult EmployeeDetail()   
  2. {  
  3.     Employee emp = TempData["Employee"] asEmployee;  
  4.     return View("Employee");  
  5. }  
Here's the complete code

code

Step 4: Right click on “EmployeeDetail” method and add view name “Employee”,

view

solution

Step 5: Add the following code in Employee View, and you can change the code accordingly:
  1. @ {  
  2.     Layout = null;  
  3. } < !DOCTYPEhtml >  
  4.     < html >  
  5.     < head >  
  6.     < meta name = "viewport"  
  7. content = "width=device-width" / >  
  8.     < title > Employee < /title> < /head> < body >  
  9.     < div >  
  10.     @   
  11.     {  
  12.         var emp = TempData["Employee"as Test.Models.Employee; < h1 > @emp.EmpID < /h1> < h2 > @emp.Name < /h2> < h3 > @emp.Designation < /h3>  
  13.   
  14.     }  
  15.   
  16. < /div>   
  17.   < /body>   
  18.   < /html>  
What I am trying to do is storing an employee object in TempData and retrieving the same in controller call. Same way, if you will try to do it with ViewBag and ViewData, you will get a null value.

Here's the final outcome:

output