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;
- }
- }
Step 3: Add a “Home Controller” and add the following code in Index method:
- Employee objEmployee = newEmployee()
- {
- Name = "Nishant",
- EmpID = "NM720501",
- Designation = "Technical Specialist"
- };
- TempData["Employee"] = objEmployee;
- return RedirectToAction("EmployeeDetail");
Create one more method name “
EmployeeDetail” and add the following code:
- public ActionResult EmployeeDetail()
- {
- Employee emp = TempData["Employee"] asEmployee;
- return View("Employee");
- }
Here's the complete code
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>
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: