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.

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:
- public class Employee
- {
- public string Name
- {
- get;
- set;
- }
- public string EmpID
- {
- get;
- set;
- }
- public string Designation
- {
- get;
- set;
- }
- }
- Employee objEmployee = newEmployee()
- {
- Name = "Nishant",
- EmpID = "NM720501",
- Designation = "Technical Specialist"
- };
- TempData["Employee"] = objEmployee;
- return RedirectToAction("EmployeeDetail");
- public ActionResult EmployeeDetail()
- {
- Employee emp = TempData["Employee"] asEmployee;
- return View("Employee");
- }

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


Step 5: Add the following code in Employee View, and you can change the code accordingly:
- @ {
- Layout = null;
- } < !DOCTYPEhtml >
- < html >
- < head >
- < meta name = "viewport"
- content = "width=device-width" / >
- < title > Employee < /title> < /head> < body >
- < div >
- @
- {
- var emp = TempData["Employee"] as Test.Models.Employee; < h1 > @emp.EmpID < /h1> < h2 > @emp.Name < /h2> < h3 > @emp.Designation < /h3>
- }
- < /div>
- < /body>
- < /html>
Here's the final outcome:


Nishant MittalPosted Jan 13, 2016, 11:09 AM
Thanks Guys..Sure will mention the difference also ..nice suggestion.......your comment accepted :)
Santhakumar MunuswamyPosted Jan 13, 2016, 9:44 AM
Thanks for sharing. I have small suggestion if you added difference b/w ViewData, ViewBag and TempData it will be better to understand for the beginner.
Gowtham KPosted Jan 13, 2016, 8:24 AM
Good One
Raja TPosted Jan 13, 2016, 6:39 AM
Nice, Thanks for sharing