Passing Data From Controller To View With TempData - Part Four

This article will tell you almost everything you need to know about passing data from Controller to View in ASP.NET MVC using TempData. I am writing this article to tell you the basic to advanced foremost concepts about ways to pass data from Controller to View. This article is the fourth one in the series named “Passing Data from Controller to View”. You’ll learn all the ways in each separate article. Stay tuned!

I would strongly recommend reading my previous articles, which will be defining the basic concepts of ASP.NET MVC.

Especially, read my consecutive previous articles in which I have taught the way of passing the data from Controller to View using ViewBag. This is the link to the previous article. Read this article, check the code after downloading, and then feel free to give your feedback.

The topics to be covered are,

  1. What is TempData?
  2. Passing the data from Controller to View using TempData
  3. Differing features of TempData from ViewBag and ViewData
  4. Maintaining the State of TempData to multiple requests

Introduction and background

As we know Controller is the class that is responsible to handle all the HTTP requests and then to execute the appropriate View. And View gives us the HTML markup that we display to the user. And for displaying anything on the View, there should be some data that is passed from Controller to View. And in this and next articles, you will learn how to pass data from Controller to View.

In this article, you’ll learn how to pass a strongly typed data from Controller to View using TempData. And, you’ll see other ways to pass data, in coming articles. So stay tuned!

What is TempData?

TempData is same as ViewBag and ViewData but also has more functionalities. It is actually a dictionary having a type TempDataDictionary and it is used to store the temporary data. TempData is also one of the properties of “ControllerBase” class so when we create a controller, that controller will automatically inherit the “Controller” abstract class and this “Controller” class inherits “ControllerBase” abstract class, that’s why we can access this TempData property in each controller. You can see in the image below the “Controller” class which inherits the “ControllerBase” class.

Passing data from Controller to View with TempData 

And in the “ControllerBase” class, the TempData property is defined, see its syntax below.

  1. namespace System.Web.Mvc  
  2. {  
  3.     /// <summary>Represents the base class for all MVC controllers.</summary>  
  4.     public abstract class ControllerBase : IController  
  5.     {  
  6.         //Other code is removed for clarity.  
  7.    
  8.         /// <summary>Gets or sets the dictionary for temporary data.</summary>  
  9.         /// <returns>The dictionary for temporary data.</returns>  
  10.         public TempDataDictionary TempData { get; set; }  
  11.     }  
  12. }  

TempData is a constrainer in which we maintain the state of consecutive requests. It internally uses session variables. But we not need to clear these variables for TempData, it automatically clears its session variables. It requires typecasting for passing complex data and checking for null values to avoid errors. Let’s look at its main and simple functionality with the help of an example.

Passing the data from Controller to View using TempData

To pass the strongly typed data from Controller to View using TempData, we have to make a model class then populate its properties with some data and then pass that data to TempData as Value and selecting Key’s name is the programmer’s choice. And then in the View, we can access the data of model class by using TempData with the pre-defined keys. Let’s create a project to take a look at an example.

Go to File then New and select “Project” option.

Passing data from Controller to View with TempData 

Then create the ASP.NET web application project as depicted below.

Passing data from Controller to View with TempData 

Then select “Empty” and tick “MVC” then click OK.

Passing data from Controller to View with TempData 

The project is created successfully.

Now create a class named as “Employee” in the Models folder, shown below.

Passing data from Controller to View with TempData 

Passing data from Controller to View with TempData

Now add some properties into this class as the code is given below.

  1. namespace DataCtoV.Models  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         [Display(Name = "Serial No")]  
  6.         public byte EmployeeId { get; set; }  
  7.    
  8.         [Display(Name = "Name")]  
  9.         public string EmployeeName { get; set; }  
  10.    
  11.         public string Address { get; set; }  
  12.    
  13.         public string Phone { get; set; }  
  14.     }  
  15. }  

Now, we’ll add a controller from where this data of an employee will pass. Let’s create a Controller, as shown below.

Passing data from Controller to View with TempData 

Then, select “MVC 5 Controller– Empty” and click Add.

Passing data from Controller to View with TempData 

Then give the name of the Controller and click on Add.

Passing data from Controller to View with TempData 

The Controller is created successfully. In this Controller, we’ll make an action method with the name of “GetEmployeeData” in which we’ll make an object of “Employee” model class and populate this object with some data. Then pass this object to the TempData with the help of key named as “employee”. The code of “EmployeeDataController” is given below.

  1. namespace DataCtoV.Controllers  
  2. {  
  3.     public class EmployeeDataController : Controller  
  4.     {  
  5.         // GET: EmployeeData  
  6.         public ActionResult GetEmployeeData()  
  7.         {  
  8.             List<Employee> emp = new List<Employee>  
  9.             {  
  10.                 new Employee  
  11.                 {  
  12.                     EmployeeId = 1,  
  13.                     EmployeeName = "John",  
  14.                     Address = "12 Fremont St. Clermont, FL 2813",  
  15.                     Phone = "+1-234-2838421"  
  16.                 },  
  17.                 new Employee  
  18.                 {  
  19.                     EmployeeId = 2,  
  20.                     EmployeeName = "Smith",  
  21.                     Address = "14 Highland Drive Fort Worth, TX 3994",  
  22.                     Phone = "+1-234-2244521"  
  23.                 },  
  24.                 new Employee  
  25.                 {  
  26.                     EmployeeId = 3,  
  27.                     EmployeeName = "Marry",  
  28.                     Address = "23 Fremont Road Milledgeville, GA 6788",  
  29.                     Phone = "+1-234-46568421"  
  30.                 }  
  31.             };  
  32.    
  33.             TempData["employee"] = emp;  
  34.    
  35.             return View();  
  36.         }  
  37.     }  
  38. }  

Because we don’t have any View named as “GetEmployeeData” in the Views folder, let’s create it. For creating a View, right click on “GetEmployeeData” method and select “Add View…” option. The following dialogue box will open, click on “Add”

Passing data from Controller to View with TempData 

The View is created successfully. Let’s write the code for it.

  1. @using DataCtoV.Models  
  2. @model IEnumerable<DataCtoV.Models.Employee>  
  3. @{  
  4.     ViewBag.Title = "Employee Data";  
  5. }  
  6.    
  7. <h3>Employee Data</h3>  
  8. <table class="table table-condensed table-hover">  
  9.     <thead>  
  10.         <tr>  
  11.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  12.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  13.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  14.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  15.         </tr>  
  16.     </thead>  
  17.     <tbody>  
  18.         @foreach (var employee in (IEnumerable<Employee>)TempData["employee"])  
  19.         {  
  20.             <tr>  
  21.                 <td>@employee.EmployeeId</td>  
  22.                 <td>@employee.EmployeeName</td>  
  23.                 <td>@employee.Address</td>  
  24.                 <td>@employee.Phone</td>  
  25.             </tr>  
  26.         }  
  27.     </tbody>  
  28. </table>  

You can see in the code that, we have made a table to represent the strongly typed data of the Employee model class. We have used foreach loop to iterate the data of each employee passed from the Controller.

To iterate the data, here we have used TempData which is calling the data from Controller with the help of key named as “employee”. And you can also see that we must have to cast the TempData to Employee.

Note
We must have to cast the TempData before using it.

Why casting?

Passing data from Controller to View with TempData 

As we know, TempData has type TempDataDictionary and this Dictionary has type “object”, and the foreach loop cannot accept variables having type “object”. In the object type, the GetEnumerator method is not defined that’s why we can’t iterate the data of Employee’s collection.

To iterate the data of Employee’s collection properly, we have to cast it to IEnumerable, because there a list/collection of Employees is coming and only in IEnumerable, the GetEnumerator is defined for iterating it properly. Hence we must have to cast it in the foreach loop. See the Error below without casting.

Passing data from Controller to View with TempData 

Ways of Casting

One way of casting the TempData is described above, which is at a time casting of TempData in the foreach loop. The code is given below.

Passing data from Controller to View with TempData 

Another way of casting the TempData is, cast the TempData in the Multi-Statement Razor Code block for C#, and then use the variable in the foreach loop. You can see code below:

Casting in the code block,

  1. @{  
  2.    ViewBag.Title = "Employee Data";  
  3.    var employeeData = (IEnumerable<Employee>)TempData["employee"];  }

Then, use the “employeeData” variable in the foreach loop, as shown below.

  1. @foreach (var employee in employeeData)  
  2.         {  
  3.             <tr>  
  4.                 <td>@employee.EmployeeId</td>  
  5.                 <td>@employee.EmployeeName</td>  
  6.                 <td>@employee.Address</td>  
  7.                 <td>@employee.Phone</td>  
  8.             </tr>  
  9.         }  

All the code of “GetEmployeeData” View is given below for your convenience.

  1. @using DataCtoV.Models  
  2. @model IEnumerable<DataCtoV.Models.Employee>  
  3. @{  
  4.     ViewBag.Title = "Employee Data";  
  5.     var employeeData = (IEnumerable<Employee>)TempData["employee"];  
  6. }  
  7.    
  8. <h3>Employee Data</h3>  
  9. <table class="table table-condensed table-hover">  
  10.     <thead>  
  11.     <tr>  
  12.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  13.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  14.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  15.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  16.         </tr>  
  17.     </thead>  
  18.     <tbody>  
  19.         @foreach (var employee in employeeData)  
  20.         {  
  21.             <tr>  
  22.                 <td>@employee.EmployeeId</td>  
  23.                 <td>@employee.EmployeeName</td>  
  24.                 <td>@employee.Address</td>  
  25.                 <td>@employee.Phone</td>  
  26.             </tr>  
  27.         }  
  28.     </tbody>  
  29. </table>  

You have seen the reason of casting and ways to do casting. Now simply, let’s build and run the application. You should see the following output.

Passing data from Controller to View with TempData 

Hence you have seen the practical example of TempData. Now let’s move towards its more features.

Differing features of TempData from ViewBag and ViewData

TempData is a container in which we maintain the state of consecutive requests. It internally uses session variables but we are not needed to clear these variables for TempData, it automatically clears its session variables. TempData stores the information only for an HTTP request mean to say from one page to another. TempData also works with 302 (Found) redirection and 301 (See Other) redirection because it’s in the same HTTP request. TempData helps to maintain the data from controller/action to another controller/action. You may say when you redirect, the TempData helps to maintain data between these redirects. Now, look at a practical example in which the redirection occurs.

For this, first, you have to make some changes in the “GetEmployeeData.cshtml” View. Comment all the code and write the following line of code.

  1. @{  
  2.     ViewBag.Title = "Employee Data";  
  3. }  
  4. <br />  
  5. @Html.ActionLink("Click for Redirection""SecondMethod""EmployeeData")   

The above line of code makes the redirection from “GetEmployeeData” action method to “SecondMethod” action method to show you that the TempData supports redirection while maintaining the data.

Now, you have to make another action method in the “EmployeeDataController” controller named as “SecondMethod”. The complete code of “EmployeeDataController” after making changes is as follows,

  1. namespace DataCtoV.Controllers  
  2. {  
  3.     public class EmployeeDataController : Controller  
  4.     {  
  5.         // GET: EmployeeData  
  6.         public ActionResult GetEmployeeData()  
  7.         {  
  8.             List<Employee> emp = new List<Employee>  
  9.             {  
  10.                 new Employee  
  11.                 {  
  12.                     EmployeeId = 1,  
  13.                     EmployeeName = "John",  
  14.                     Address = "12 Fremont St. Clermont, FL 2813",  
  15.                     Phone = "+1-234-2838421"  
  16.                 },  
  17.                 new Employee  
  18.                 {  
  19.                     EmployeeId = 2,  
  20.                     EmployeeName = "Smith",  
  21.                     Address = "14 Highland Drive Fort Worth, TX 3994",  
  22.                     Phone = "+1-234-2244521"  
  23.                 },  
  24.                 new Employee  
  25.                 {  
  26.                     EmployeeId = 3,  
  27.                     EmployeeName = "Marry",  
  28.                     Address = "23 Fremont Road Milledgeville, GA 6788",  
  29.                     Phone = "+1-234-46568421"  
  30.                 }  
  31.             };  
  32.    
  33.             TempData["employee"] = emp;  
  34.    //We have to use keep function if we want to print data at   
  35.    //"GetEmployeeData.cshtml"  
  36.    TempData.Keep();  
  37.   
  38.             return View();  
  39.         }  
  40.    
  41.         public ActionResult SecondMethod()  
  42.         {  
  43.             //The second method is used to show redirection in TempData.  
  44.             ViewBag.emp = TempData["employee"];  
  45.             return View();  
  46.         }  
  47.     }  
  48. }  

Now, we have to make the SecondMethod.cshtml view file in the Views folder. After making, the code will be as shown below.

  1. @model DataCtoV.Models.Employee  
  2. @{  
  3.     ViewBag.Title = "Second";  
  4. }  
  5.    
  6. <h2>Second</h2>  
  7.    
  8. <table class="table table-condensed table-hover">  
  9.     <thead>  
  10.         <tr>  
  11.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  12.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  13.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  14.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  15.         </tr>  
  16.     </thead>  
  17.     <tbody>  
  18.         @foreach (var employee in ViewBag.emp)  
  19.         {  
  20.             <tr>  
  21.                 <td>@employee.EmployeeId</td>  
  22.                 <td>@employee.EmployeeName</td>  
  23.                 <td>@employee.Address</td>  
  24.                 <td>@employee.Phone</td>  
  25.             </tr>  
  26.         }  
  27.     </tbody>  
  28. </table>  

Now, simply build and run the application for this URL - /EmployeeData/GetEmployeeData. You should see the following output.

Passing data from Controller to View with TempData 

When you click on the link, you will redirect from the “GetEmployeeData” action method to the “SecondMethod” action method. And the output will be like below.

Passing data from Controller to View with TempData 

Hence you have seen the redirection while maintaining data using TempData. This is the feature that makes TempData different from ViewBag and ViewData because this feature is not present in ViewBag and ViewData.

Maintaining the State of TempData to multiple requests

In the previous section, you have maintained the state of data at the first request and made values accessible at second request. Now if you want to maintain the state up to third, fourth, and so on requests, then how can you do it?

This can be done by using a built-in “Keep” function with the TempData variables. Let’s look at its practical example by making some changes into “DataCtoV” project. So we make changes in “SecondMethod” by using the “Keep” function to maintain the state of data.

  1. public ActionResult SecondMethod()  
  2. {  
  3.     //The second method is used to show redirection in TempData.  
  4.     ViewBag.emp = TempData["employee"];  
  5.   
  6.     //To maintain the state of TempData  
  7.     TempData.Keep();  
  8.   
  9.     return View();  
  10. }  

Then go to its View named as “SecondMethod.cshtml” and add the following line of code to enable the redirection of request.

  1. @Html.ActionLink("Click for 2nd redirection","ThirdMethod","EmployeeData")  

And then, add another action method named as “ThirdMethod” into the “EmployeeDataController”. Code of “ThirdMethod” is as follows,

  1. public ActionResult ThirdMethod()  
  2.        {  
  3.            //The third method is used to show redirection and  
  4.            //maintaining data up to multiple requests in TempData.  
  5.            ViewBag.third = TempData["employee"];  
  6.            return View();  
  7.        }  

Now, create its view and place the following code in it.

  1. @model DataCtoV.Models.Employee  
  2. @{  
  3.     ViewBag.Title = "ThirdMethod";  
  4. }  
  5.    
  6. <h2>ThirdMethod</h2>  
  7.    
  8. <table class="table table-condensed table-hover">  
  9.     <thead>  
  10.     <tr>  
  11.         <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  12.         <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  13.         <th>@Html.DisplayNameFor(e => e.Address)</th>  
  14.         <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  15.     </tr>  
  16.     </thead>  
  17.     <tbody>  
  18.     @foreach (var employee in ViewBag.third)  
  19.     {  
  20.         <tr>  
  21.             <td>@employee.EmployeeId</td>  
  22.             <td>@employee.EmployeeName</td>  
  23.             <td>@employee.Address</td>  
  24.             <td>@employee.Phone</td>  
  25.         </tr>  
  26.     }  
  27.     </tbody>  
  28. </table>  

Now, I am providing the full code of each file only for your convenience.

The complete code of “Employee” model class is as below.

  1. namespace DataCtoV.Models  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         [Display(Name = "Serial No")]  
  6.         public byte EmployeeId { get; set; }  
  7.    
  8.         [Display(Name = "Name")]  
  9.         public string EmployeeName { get; set; }  
  10.    
  11.         public string Address { get; set; }  
  12.    
  13.         public string Phone { get; set; }  
  14.     }  
  15. }  

The complete code of “EmployeeDataController” is given below.

  1. namespace DataCtoV.Controllers  
  2. {  
  3.     public class EmployeeDataController : Controller  
  4.     {  
  5.         // GET: EmployeeData  
  6.         public ActionResult GetEmployeeData()  
  7.         {  
  8.             List<Employee> emp = new List<Employee>  
  9.             {  
  10.                 new Employee  
  11.                 {  
  12.                     EmployeeId = 1,  
  13.                     EmployeeName = "John",  
  14.                     Address = "12 Fremont St. Clermont, FL 2813",  
  15.                     Phone = "+1-234-2838421"  
  16.                 },  
  17.                 new Employee  
  18.                 {  
  19.                     EmployeeId = 2,  
  20.                     EmployeeName = "Smith",  
  21.                     Address = "14 Highland Drive Fort Worth, TX 3994",  
  22.                     Phone = "+1-234-2244521"  
  23.                 },  
  24.                 new Employee  
  25.                 {  
  26.                     EmployeeId = 3,  
  27.                     EmployeeName = "Marry",  
  28.                     Address = "23 Fremont Road Milledgeville, GA 6788",  
  29.                     Phone = "+1-234-46568421"  
  30.                 }  
  31.             };  
  32.    
  33.             TempData["employee"] = emp;  
  34.    
  35.             return View();  
  36.         }  
  37.    
  38.         public ActionResult SecondMethod()  
  39.         {  
  40.             //The second method is used to show redirection in TempData.  
  41.             ViewBag.emp = TempData["employee"];  
  42.    
  43.             //To maintain the state of TempData  
  44.             TempData.Keep();  
  45.    
  46.             return View();  
  47.         }  
  48.    
  49.         public ActionResult ThirdMethod()  
  50.         {  
  51.             //The third method is used to show redirection and  
  52.             //maintaining data up to multiple requests in TempData.  
  53.             ViewBag.third = TempData["employee"];  
  54.             return View();  
  55.         }  
  56.    
  57.     }  
  58. }  

The complete code of “GetEmployeeData.cshtml” view is as below.

  1. @using DataCtoV.Models  
  2. @model IEnumerable<DataCtoV.Models.Employee>  
  3. @{  
  4.     ViewBag.Title = "Employee Data";  
  5.     var employeeData = (IEnumerable<Employee>)TempData["employee"];  
  6. }  
  7.    
  8. <h3>Employee Data</h3>  
  9. <br />  
  10. @Html.ActionLink("Click for first Redirection""SecondMethod""EmployeeData")  
  11.    
  12. <table class="table table-condensed table-hover">  
  13.     <thead>  
  14.         <tr>  
  15.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  16.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  17.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  18.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  19.         </tr>  
  20.     </thead>  
  21.     <tbody>  
  22.         @foreach (var employee in employeeData)  
  23.         {  
  24.             <tr>  
  25.                 <td>@employee.EmployeeId</td>  
  26.                 <td>@employee.EmployeeName</td>  
  27.                 <td>@employee.Address</td>  
  28.                 <td>@employee.Phone</td>  
  29.             </tr>  
  30.         }  
  31.     </tbody>  
  32. </table>  

Complete code of “SecondMethod” is follows,

  1. @model DataCtoV.Models.Employee  
  2. @{  
  3.     ViewBag.Title = "Second";  
  4. }  
  5.    
  6. <h2>Second</h2>  
  7.    
  8. @Html.ActionLink("Click for 2nd redirection""ThirdMethod""EmployeeData")  
  9.    
  10. <table class="table table-condensed table-hover">  
  11.     <thead>  
  12.         <tr>  
  13.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  14.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  15.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  16.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  17.         </tr>  
  18.     </thead>  
  19.     <tbody>  
  20.         @foreach (var employee in ViewBag.emp)  
  21.         {  
  22.             <tr>  
  23.                 <td>@employee.EmployeeId</td>  
  24.                 <td>@employee.EmployeeName</td>  
  25.                 <td>@employee.Address</td>  
  26.                 <td>@employee.Phone</td>  
  27.             </tr>  
  28.         }  
  29.     </tbody>  
  30. </table>  

Complete code of “ThirdMethod” is as follows,

  1. @model DataCtoV.Models.Employee  
  2.     @{  
  3.         ViewBag.Title = "ThirdMethod";  
  4.     }  
  5.    
  6.     <h2>ThirdMethod</h2>  
  7.    
  8.     <table class="table table-condensed table-hover">  
  9.         <thead>  
  10.             <tr>  
  11.                 <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  12.                 <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  13.                 <th>@Html.DisplayNameFor(e => e.Address)</th>  
  14.                 <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  15.             </tr>  
  16.         </thead>  
  17.         <tbody>  
  18.             @foreach (var employee in ViewBag.third)  
  19.             {  
  20.                 <tr>  
  21.                     <td>@employee.EmployeeId</td>  
  22.                     <td>@employee.EmployeeName</td>  
  23.                     <td>@employee.Address</td>  
  24.                     <td>@employee.Phone</td>  
  25.                 </tr>  
  26.             }  
  27.         </tbody>  
  28.     </table>  

Now, simply build and run the application with the URL /EmployeeData/GetEmployeeData to see the output. Output should be as follows,

Passing data from Controller to View with TempData 

Just click on the link “Click for first Redirection” then its corresponding HTTP request will execute and give the following output.

Passing data from Controller to View with TempData 

Above is the first redirection in which the state of TempData is maintained. And this data will pass to “ThirdMethod” after clicking on the link “Click for 2nd redirection” then the output will be like this. 

Passing data from Controller to View with TempData 

Hence in this way, you can maintain the state of TempData up to multiple requests.

Summary

In this article, you have learned that how to pass strongly typed data from Controller to View using TempData, in which firstly, you should make a model class then populate its properties with some data then pass that object to the TempData as Value and pass magic Key as a string. Then you have looked the main differing feature of TempData with ViewBag and ViewData. Also, you have learned how to maintain the state of TempData up to multiple requests.

Conclusion

I hope this article has helped you in understanding the concepts about passing strongly typed data from Controller to View using TempData in ASP.NET MVC. Stay tuned for my next articles because this article is the fourth one in the series of “Passing data from Controller to View” and you’ll learn more about passing data in coming articles. If you have any query, please feel free to contact me in the comments section. Also, do provide the feedback whether positive or negative. It will help me to make my articles better and increase my enthusiasm to share my knowledge.


Similar Articles