ViewData, ViewBag & TempData in ASP.NET MVC 5

Introduction

 
In this article, we will see different ways of passing the Model data from Controller to View. We know to pass the data from Controller to View we use View() method to return ViewResult return type. Apart from View() method we can use different ways to return the data.
 
There are three different ways of returning the data from Controller to View or .cshtml file as shown below. 
 

ViewData

 
ViewData is used for returning the data from Controller's action method to View or .cshtml file. ViewData is a dictionary or it's a property with get & set accessors, which is part of ControllerBase class. ViewDataDictionary class inherits from IDictionary<string, object> interface and ViewData returns ViewDataDictionary class object, that means ViewData is a collection of Dictionary objects with string, object types. ViewData's data can be accessed in the current page instance. If there is any navigation from one view to another view then there may be chances of losing the data from ViewData object.
 
 
 
 
 
 
In Controller's Action Method in order to assign the Model data to ViewData dictionary object, in the below syntax I am using employee object as well as list of employee objects to store in ViewData dictionary object and return ViewData to the View or .cshtml and binds it to the HTML table.
 
Syntax
  1. Employee employeeObj = new Employee();  
  2. ViewData["EmployeeObject"] = employeeObj;   
From the above example on the right hand side we need to pass or assign the employee object which we get from database and stored in Model class.
 
If we want to assign the list of Employee object we need to assign like below.
  1. List<Employee> listOfEmployees = new List<Employee>();  
  2. ViewData["EmployeeListObject"] = listOfEmployees;   
Here on the right hand side we need to pass the list of employee object, if we want to pass the list of employees from Controler to View or .cshtml file.
 

ViewBag

 
ViewBag is used for returning the data from Controller to View. ViewBag is a property with only get accessor which is a member of ControllerBase abstract class with dynamic type. It is similar to ViewData. ViewBag object data can be accessed in the current page instance. If there is any navigation from one view to another view then there may be chances of losing the data from ViewBag object.
 
 
 
In Controller's Action Method in order to assign the Model data to ViewBag object we assign as shown below. In the below syntax, I am using employee object as well as a  list of employee objects to store the data in ViewBag object and return ViewBag to the View or .cshtml and bind it to the HTML table.
 
Syntax
  1. Employee employeeObj = new Employee();  
  2. ViewBag.EmployeeObject = employeeObj;   
From the above example on the right hand side we need to pass the employee object which we get from database and stored in Model class.
 
If we want to assign the list of Employee objects we need to assign like below.
  1. List<Employee> listOfEmployees = new List<Employee>();  
  2. ViewBag.EmployeeListObject = listOfEmployees;
Here on the right hand side we need to pass the list of employee objects, if we want to pass the list of employees from controller to view or .cshtml file.
 

TempData

 
Using TempData we can pass the data from Controller's Action Method to View or .cshtml file. It is similar to ViewData.
 
TempData is a dictionary of objects or a property with get and set accessors which is a member of ControllerBase abstract class.
 
TempData has a return type TempDataDictionary class and TempDataDictionary class inherits from
 
IDictionary<string, object> interface that means TempData is a collection of Dictionary object with string, object types.
 
 
 
 
 
Whenever there is any navigation from one View to another View, TempData object's data will be available and can be accessed in redirection of pages.
 
It is different from ViewData and ViewBag, In ViewData and ViewBag whenever there is any navigation or redirection of webpage then the data will not be available.
 
But the data will be available even during the redirection of webpages in TempData.
 
In Controller's Action Method in order to assign the Model data to TempData object, in the below syntax, I am using employee object as well as list of employee objects to store in TempData object and return TempData to the View or .cshtml and bind the data to the HTML table.
 
Syntax
  1. Employee employeeObj = new Employee();  
  2. TempData["EmployeeObject"] = employeeObj;  
From the above example on the right hand side we need to pass the employee object which we get from database and stored in Model class.
 
If we want to assign the list of Employee object we need to assign like below.
  1. List<Employee> listOfEmployees = new List<Employee>();  
  2. TempData["EmployeeListObject"] = listOfEmployees; 
Here on the right hand side we need to pass the list of employee objects, if we want to pass the list of employees from Controler to View or .cshtml file.
 
Let's Create ASP.NET MVC 5 Application and Create a Project in order to understand ViewData, ViewBag & TempData.
 
I am using Visual Studio 2019 community edition to create a sample project, you can use any version of your choice.
 
Step 1: Open Visual Studio 2019 and click on Create a new project on the bottom right as shown below.
 
 
 
Step 2: Search ASP.NET Web Application in the above-provided textbox and click on the template and click on the Next button as shown below.
 
 
 
Step 3: Provide the Project name as you wish, I have used project name as MVCFirstProject and click on Create button.
 
 
 
Step 4: Select the MVC template and click on the Create button, with this a new MVC project is Created.
 
Once the ASP.NET 5 Application is created, we need to Create a Model to use in our application, in this example I will assign the object with some hardcoded values.
 
In order to create a Model, right click on Models folder then click on Add, select the class template and give the name as Employee.cs and click on Add button.
With this Employee.cs Model will be created in Models folder.
 
Open the Employee.cs file and paste the properties as shown below. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MVCViewData.Models  
  7. {  
  8.     public class Employee  
  9.     {  
  10.         public int EmployeeId { getset; }  
  11.         public string EmployeeName { getset; }  
  12.         public string EmployeeDesignation { getset; }  
  13.         public string DateOfJoining { getset; }  
  14.         public int EmployeePhone { getset; }  
  15.         public string EmployeeGender { getset; }  
  16.         public string City { getset; }  
  17.         public string Project { getset; }  
  18.         public string CompanyName { getset; }  
  19.     }  
  20. }  
 
 
In order to create a EmployeeController, right click on Controller's folder, click on Add and click on Controller, with this Add Scaffold template will be opened, in this
select mvc 5 Controller - Empty and click on Add button. In Add Controller window, give the Controller name as EmployeeController and click on Add button. With this
EmployeeController will be created in Controllers folder.
 
Now open the EmployeeController.cs class and paste the below code. 
  1. using MVCViewData.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace MVCViewData.Controllers  
  9. {  
  10.     public class EmployeeController : Controller  
  11.     {  
  12.         List<Employee> listEmployee = new List<Employee>();  
  13.         Employee employee = new Employee();  
  14.         // GET: Employee  
  15.         public ActionResult ViewDataTest()  
  16.         {  
  17.             AssigningValues();  
  18.             ViewData["EmployeeInfo"] = employee;  
  19.             ViewData["EmployeesInfo"] = listEmployee;  
  20.   
  21.             return View();  
  22.         }  
  23.   
  24.         public ActionResult ViewBagTest()  
  25.         {  
  26.             AssigningValues();  
  27.             ViewBag.EmployeeInfo = employee;  
  28.             ViewBag.EmployeesInfo = listEmployee;  
  29.   
  30.             return View();  
  31.         }  
  32.   
  33.         public ActionResult TempDataTest()  
  34.         {  
  35.             AssigningValues();  
  36.             TempData["EmployeeInfo"] = employee;  
  37.             TempData["EmployeesInfo"] = listEmployee;  
  38.   
  39.             return View();  
  40.         }  
  41.   
  42.         private void AssigningValues()  
  43.         {  
  44.             employee.EmployeeId = 1001;  
  45.             employee.EmployeeName = "Khaja";  
  46.             employee.EmployeeDesignation = "SE";  
  47.             employee.DateOfJoining = "22/05/2015";  
  48.             employee.EmployeePhone = 806980474;  
  49.             employee.EmployeeGender = "Male";  
  50.             employee.City = "Hyderabad";  
  51.             employee.Project = "AILabz";  
  52.             employee.CompanyName = "ValueLabs";  
  53.   
  54.   
  55.   
  56.   
  57.   
  58.             listEmployee.Add(new Employee()  
  59.             {  
  60.                 EmployeeId = 1001,  
  61.             EmployeeName = "Khaja",  
  62.             EmployeeDesignation = "SE",  
  63.             DateOfJoining = "22/05/2015",  
  64.             EmployeePhone = 806980474,  
  65.             EmployeeGender = "Male",  
  66.             City = "Hyderabad",  
  67.             Project = "AILabz",  
  68.             CompanyName = "ValueLabs",  
  69.         });  
  70.   
  71.             listEmployee.Add(new Employee()  
  72.             {  
  73.                 EmployeeId = 1002,  
  74.                 EmployeeName = "Vijay",  
  75.                 EmployeeDesignation = "S.SE",  
  76.                 DateOfJoining = "10/05/2013",  
  77.                 EmployeePhone = 907846532,  
  78.                 EmployeeGender = "Male",  
  79.                 City = "Hyderabad",  
  80.                 Project = "AutomationTool",  
  81.                 CompanyName = "Accenture",  
  82.             });  
  83.   
  84.             listEmployee.Add(new Employee()  
  85.             {  
  86.                 EmployeeId = 1003,  
  87.                 EmployeeName = "Vikas",  
  88.                 EmployeeDesignation = "TeamLead",  
  89.                 DateOfJoining = "01/10/2012",  
  90.                 EmployeePhone = 798534120,  
  91.                 EmployeeGender = "Male",  
  92.                 City = "Bangalore",  
  93.                 Project = "AzureDevOps",  
  94.                 CompanyName = "Cognizant",  
  95.             });  
  96.         }  
  97.     }  
  98. }  
In the above code I have an Employee as well List<Employee> objects. In EmployeeController we have three different Action methods as well as  a normal method AssigningValues() like
 
ViewDataTest
ViewBagTest &
TempDataTest
 
In these Action Methods we are using three different ways of returning the data to the View() or .cshtml file as shown above.
 
In AssigningValues method, I am assigning the Employee object and List of Employees objects. In ViewDataTest() method i am calling AssigningValues() method, with this Employee and list of Employee objects will be assigned with data. With this data, I am assigning it to ViewData dictionary object.
 
Similarly for ViewBagTest and TempDataTest I am doing the same thing what I did for ViewDataTest() method.
 
Whenever we create a Controller say EmployeeController with three different action methods, then a new folder will be created in Views folder with three different Views or .cshtml files
 
The folder which will be created in Views folder has the same name as Controller's name and View() or .cshtml files have the same name as Action Methods.
 
The Folder structure of Views as shown below.
 
Views--> Employee-->ViewDataTest.cshtml
Views--> Employee-->ViewBagTest.cshtml
Views--> Employee-->TempDataTest.cshtml
 
In order to create ViewDataTest.cshtml View, right click on the ViewDataTest Action method, click on Add View, with this AddView window will be opened, give the View Name as ViewDataTest and click on Add.
 
With this ViewDataTest.cshtml will be created, now open the ViewDataTest.cshtml file and paste the below code. 
  1. @{  
  2.     ViewBag.Title = "ViewDataTest";  
  3.     var employeeInfo = ViewData["EmployeeInfo"as MVCViewData.Models.Employee;  
  4. }  
  5.   
  6. <h2>ViewDataTest</h2>  
  7.   
  8. <hr>  
  9.   
  10. <h3>Employee Information Using ViewData</h3>  
  11. <table>  
  12.     <tr>  
  13.         <th>Employee Id</th>  
  14.         <th>Employee Name</th>  
  15.         <th>Employee Designation</th>  
  16.         <th>Date Of Joining</th>  
  17.         <th>Employee Phone</th>  
  18.         <th>Employee Gender</th>  
  19.         <th>City</th>  
  20.         <th>Project</th>  
  21.         <th>Company Name</th>  
  22.     </tr>  
  23.   
  24.     <tr>  
  25.         <td>@employeeInfo.EmployeeId</td>  
  26.         <td>@employeeInfo.EmployeeName</td>  
  27.         <td>@employeeInfo.EmployeeDesignation</td>  
  28.         <td>@employeeInfo.DateOfJoining</td>  
  29.         <td>@employeeInfo.EmployeePhone</td>  
  30.         <td>@employeeInfo.EmployeeGender</td>  
  31.         <td>@employeeInfo.City</td>  
  32.         <td>@employeeInfo.Project</td>  
  33.         <td>@employeeInfo.CompanyName</td>  
  34.     </tr>  
  35. </table>  
  36.   
  37. <h3>Employees Information Using ViewData</h3>  
  38. <table>  
  39.     <tr>  
  40.         <th>Employee Id</th>  
  41.         <th>Employee Name</th>  
  42.         <th>Employee Designation</th>  
  43.         <th>Date Of Joining</th>  
  44.         <th>Employee Phone</th>  
  45.         <th>Employee Gender</th>  
  46.         <th>City</th>  
  47.         <th>Project</th>  
  48.         <th>Company Name</th>  
  49.     </tr>  
  50.       
  51.         @foreach (var eachEmployee in ViewData["EmployeesInfo"as List<MVCViewData.Models.Employee>)  
  52.         {  
  53.             <tr>  
  54.   
  55.                 <td>@eachEmployee.EmployeeId</td>  
  56.                 <td>@eachEmployee.EmployeeName</td>  
  57.                 <td>@eachEmployee.EmployeeDesignation</td>  
  58.                 <td>@eachEmployee.DateOfJoining</td>  
  59.                 <td>@eachEmployee.EmployeePhone</td>  
  60.                 <td>@eachEmployee.EmployeeGender</td>  
  61.                 <td>@eachEmployee.City</td>  
  62.                 <td>@eachEmployee.Project</td>  
  63.                 <td>@eachEmployee.CompanyName</td>  
  64.             </tr>  
  65.         }  
  66.       
  67.     </table>  
  68.   
  69.   
  70.   
  71.     <style>  
  72.         table {  
  73.             font-family: arial, sans-serif;  
  74.             border-collapse: collapse;  
  75.             width: 100%;  
  76.         }  
  77.   
  78.         td, th {  
  79.             border: 1px solid #dddddd;  
  80.             text-align: left;  
  81.             padding: 8px;  
  82.         }  
  83.     </style>  
In the above code I used var employeeInfo = ViewData["EmployeeInfo"] as MVCViewData.Models.Employee;
 
The ViewData["EmployeeInfo"] will have Employee object which is passed from ViewDataTest Controller. Here I am Converting ViewData["EmployeeInfo"] as Employee.cs Model and assigning it to employeeInfo.
 
Similarly in the above code I used @foreach (var eachEmployee in ViewData["EmployeesInfo"] as List<MVCViewData.Models.Employee>).
 
Here ViewData["EmployeesInfo"] data will be getting from ViewDataTest Action Method. I am converting ViewData["EmployeesInfo"] as List<Employee> object and iterating one by one through list of employees and binding it to the HTML table.
 
In order to create ViewBagTest.cshtml View, right click on the ViewBagTest Action Method, click on Add View, with this AddView window will be opened, give the View Name as ViewBagTest and click on Add.
 
With this ViewBagTest.cshtml will be created, now open the ViewBagTest.cshtml file and paste the below code. 
  1. <h2>ViewBagTest</h2>  
  2.   
  3. <hr>  
  4.   
  5. @{  
  6.     ViewBag.Title = "ViewBagTest";  
  7.     var employeeInfo = ViewBag.EmployeeInfo as MVCViewData.Models.Employee;  
  8. }  
  9.   
  10.   
  11. <h3>Employee Information Using ViewBag</h3>  
  12. <table>  
  13.     <tr>  
  14.         <th>Employee Id</th>  
  15.         <th>Employee Name</th>  
  16.         <th>Employee Designation</th>  
  17.         <th>Date Of Joining</th>  
  18.         <th>Employee Phone</th>  
  19.         <th>Employee Gender</th>  
  20.         <th>City</th>  
  21.         <th>Project</th>  
  22.         <th>Company Name</th>  
  23.     </tr>  
  24.   
  25.     <tr>  
  26.         <td>@employeeInfo.EmployeeId</td>  
  27.         <td>@employeeInfo.EmployeeName</td>  
  28.         <td>@employeeInfo.EmployeeDesignation</td>  
  29.         <td>@employeeInfo.DateOfJoining</td>  
  30.         <td>@employeeInfo.EmployeePhone</td>  
  31.         <td>@employeeInfo.EmployeeGender</td>  
  32.         <td>@employeeInfo.City</td>  
  33.         <td>@employeeInfo.Project</td>  
  34.         <td>@employeeInfo.CompanyName</td>  
  35.     </tr>  
  36. </table>  
  37.   
  38. <h3>Employees Information Using ViewBag</h3>  
  39. <table>  
  40.     <tr>  
  41.         <th>Employee Id</th>  
  42.         <th>Employee Name</th>  
  43.         <th>Employee Designation</th>  
  44.         <th>Date Of Joining</th>  
  45.         <th>Employee Phone</th>  
  46.         <th>Employee Gender</th>  
  47.         <th>City</th>  
  48.         <th>Project</th>  
  49.         <th>Company Name</th>  
  50.     </tr>  
  51.   
  52.     @foreach (var eachEmployee in ViewBag.EmployeesInfo as List<MVCViewData.Models.Employee>)  
  53.     {  
  54.         <tr>  
  55.   
  56.             <td>@eachEmployee.EmployeeId</td>  
  57.             <td>@eachEmployee.EmployeeName</td>  
  58.             <td>@eachEmployee.EmployeeDesignation</td>  
  59.             <td>@eachEmployee.DateOfJoining</td>  
  60.             <td>@eachEmployee.EmployeePhone</td>  
  61.             <td>@eachEmployee.EmployeeGender</td>  
  62.             <td>@eachEmployee.City</td>  
  63.             <td>@eachEmployee.Project</td>  
  64.             <td>@eachEmployee.CompanyName</td>  
  65.         </tr>  
  66.     }  
  67.   
  68. </table>  

  69. <style>  
  70.     table {  
  71.         font-family: arial, sans-serif;  
  72.         border-collapse: collapse;  
  73.         width: 100%;  
  74.     }  
  75.   
  76.     td, th {  
  77.         border: 1px solid #dddddd;  
  78.         text-align: left;  
  79.         padding: 8px;  
  80.     }  
  81. </style>  
Similarly to Create TempDataTest.cshtml View, right click on the TempDataTest Action Method, click on Add View, with this AddView window will be opened, give the View Name as TempDataTest and click on Add.
 
With this TempDataTest.cshtml will be created, now open the TempDataTest.cshtml file and paste the below code. 
  1. @{  
  2.     ViewBag.Title = "TempDataTest";  
  3.     var employeeInfo = TempData["EmployeeInfo"as MVCViewData.Models.Employee;  
  4. }  
  5.   
  6. <h2>TempDataTest</h2>  
  7. <hr>  
  8.   
  9. <h3>Employee Information Using TempData</h3>  
  10. <table>  
  11.     <tr>  
  12.         <th>Employee Id</th>  
  13.         <th>Employee Name</th>  
  14.         <th>Employee Designation</th>  
  15.         <th>Date Of Joining</th>  
  16.         <th>Employee Phone</th>  
  17.         <th>Employee Gender</th>  
  18.         <th>City</th>  
  19.         <th>Project</th>  
  20.         <th>Company Name</th>  
  21.     </tr>  
  22.   
  23.     <tr>  
  24.         <td>@employeeInfo.EmployeeId</td>  
  25.         <td>@employeeInfo.EmployeeName</td>  
  26.         <td>@employeeInfo.EmployeeDesignation</td>  
  27.         <td>@employeeInfo.DateOfJoining</td>  
  28.         <td>@employeeInfo.EmployeePhone</td>  
  29.         <td>@employeeInfo.EmployeeGender</td>  
  30.         <td>@employeeInfo.City</td>  
  31.         <td>@employeeInfo.Project</td>  
  32.         <td>@employeeInfo.CompanyName</td>  
  33.     </tr>  
  34. </table>  
  35.   
  36. <h3>Employees Information Using TempData</h3>  
  37. <table>  
  38.     <tr>  
  39.         <th>Employee Id</th>  
  40.         <th>Employee Name</th>  
  41.         <th>Employee Designation</th>  
  42.         <th>Date Of Joining</th>  
  43.         <th>Employee Phone</th>  
  44.         <th>Employee Gender</th>  
  45.         <th>City</th>  
  46.         <th>Project</th>  
  47.         <th>Company Name</th>  
  48.     </tr>  
  49.   
  50.     @foreach (var eachEmployee in TempData["EmployeesInfo"as List<MVCViewData.Models.Employee>)  
  51.     {  
  52.         <tr>  
  53.   
  54.             <td>@eachEmployee.EmployeeId</td>  
  55.             <td>@eachEmployee.EmployeeName</td>  
  56.             <td>@eachEmployee.EmployeeDesignation</td>  
  57.             <td>@eachEmployee.DateOfJoining</td>  
  58.             <td>@eachEmployee.EmployeePhone</td>  
  59.             <td>@eachEmployee.EmployeeGender</td>  
  60.             <td>@eachEmployee.City</td>  
  61.             <td>@eachEmployee.Project</td>  
  62.             <td>@eachEmployee.CompanyName</td>  
  63.         </tr>  
  64.     }  
  65.   
  66. </table>  

  67. <style>  
  68.     table {  
  69.         font-family: arial, sans-serif;  
  70.         border-collapse: collapse;  
  71.         width: 100%;  
  72.     }  
  73.   
  74.     td, th {  
  75.         border: 1px solid #dddddd;  
  76.         text-align: left;  
  77.         padding: 8px;  
  78.     }  
  79. </style>  
Now build and run the application by navigating to three different URL's like below.
 
http://localhost:51586/Employee/ViewDataTest
http://localhost:51586/Employee/ViewBagTest
http://localhost:51586/Employee/TempDataTest
 
When the user navigates to the first URL then the EmployeeController ViewDataTest will handle the request and give the result as shown below.
 
 
 
When user navigates to the second URL, then EmployeeController ViewBagTest will handle the request and gives the result as shown below.
 
 
 
Similarly when user navigates to the third URL, then EmployeeController TempDataTest will handle the request and gives the result as shown below.
 
 
 
Thanks for reading my article, I hope this article helps you.


Similar Articles