Learn About ViewData, ViewBag And TempData In ASP.NET MVC

In this article, you will learn about ViewData, ViewBag and TempData in ASP.NET MVC.

Introduction

 
In this article, you will learn about ViewData, ViewBag and TempData in ASP.NET MVC.
ViewData
 
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. It is useful in transferring data from Controller to View.
 
ViewBag
 
ViewBag is actually a wrapper around ViewData. ViewBag transfers data from the controller to the view, ideally temporary data which is not included in a model.
 
TempData
 
TempData can be used to store data between two consecutive requests. TempData values will be retained during redirection.
 

Difference between ViewData, ViewBag and TempData

 
ViewData
  1. ViewData is a dictionary object that is derived from ViewDataDictionary class.
  2. ViewData is a property of ControllerBase class.
  3. ViewData is used to pass data from controller to corresponding view.
  4. Its life lies only during the current request.
  5. If redirection occurs then its value becomes null.
  6. Its required typecasting for getting data and checking for null values to avoid error.
ViewBag
  1. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  2. Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
  3. ViewBag is a property of ControllerBase class.
  4. Its life also lies only during the current request.
  5. If redirection occurs then its value becomes null.
  6. It doesn’t required typecasting for getting data.
TempData
  1. TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
  2. TempData is a property of ControllerBase class.
  3. TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
  4. Its life is very short and lies only till the target view is fully loaded.
  5. It’s required typecasting for getting data and check for null values to avoid error.
  6. It is used to store only one time messages like error messages, validation messages. To persist data with TempData refer this article.
Step 1
 
Open up your favorite SQL Server database with any version. It really doesn’t matter what version it is. Create the following database data tables.
  1. create table Employee  
  2. (  
  3.    Id int primary key identity(1,1),  
  4.    Name nvarchar(50),  
  5.    Gender char(10),  
  6.    Age int,  
  7.    Position nvarchar(50),  
  8.    Office nvarchar(50),  
  9.    Salary int  
  10. )  
  11.   
  12. insert into Employee values('Arvind Kumar','Male',30,'Software Developer','Bangalore',55000)  
  13. insert into Employee values('Divya','Female',25,'Designer','Bangalore',50000)  
  14. insert into Employee values('Rahul Sharma','Male',28,'UI Developer','Bangalore',45000)  
  15. insert into Employee values('Monica','Female',35,'Angular Developer','Bangalore',60000)  
  16. insert into Employee values('Vinay Kumar','Male',32,'Software Developer','Bangalore',70000)  
Step 2
 
Open Visual Studio 2015 or an editor of your choice and create a new project.
 
Step 3
 
Choose "web application" project and give an appropriate name to your project.
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
Step 4
 
Select "empty" template, check on the MVC box, and click OK.
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
Step 5
 
Right-click the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select "New Item"
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
Entity Framework gets added and the respective class gets generated under the Models folder.
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC 
 
Step 6
 
Right-click on Controllers folder and add a controller.
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
A window will appear. Choose MVC5 Controller-Empty and click "Add".
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC
 
Controller code
  1. using MvcViewDataViewBagTempData_Demo.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 MvcViewDataViewBagTempData_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext = new EmployeeContext();  
  13.   
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             ViewData["Employee"] = employee;  
  18.             ViewData["Heading"]= "List of Employee";  
  19.             return View();  
  20.         }  
  21.     }  
  22. }  
Step 7
 
Right click on index action method of HomeController.
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC 
  1. @using MvcViewDataViewBagTempData_Demo.Models;  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h3>@ViewData["Heading"]</h3>  
  8. <table class="table table-bordered">  
  9.     <thead>  
  10.         <tr>  
  11.             <th>Id</th>  
  12.             <th>Name</th>  
  13.             <th>Gender</th>  
  14.             <th>Age</th>  
  15.             <th>Position</th>  
  16.             <th>Office</th>  
  17.             <th>Salary</th>  
  18.         </tr>  
  19.     </thead>  
  20.     <tbody>  
  21.         @foreach (var emp in (ViewData["Employee"] as List<Employee>))  
  22.         {  
  23.             <tr>  
  24.                 <td>@emp.Id</td>  
  25.                 <td>@emp.Name</td>  
  26.                 <td>@emp.Gender</td>  
  27.                 <td>@emp.Age</td>  
  28.                 <td>@emp.Position</td>  
  29.                 <td>@emp.Office</td>  
  30.                 <td>@emp.Salary</td>  
  31.             </tr>  
  32.         }  
  33.     </tbody>  
  34. </table>  
ViewBag Controller Code
  1. using MvcViewDataViewBagTempData_Demo.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 MvcViewDataViewBagTempData_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext = new EmployeeContext();  
  13.   
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             ViewBag.Employee = employee;  
  18.             ViewBag.Heading = "List of Employee";  
  19.             return View();  
  20.         }  
  21.     }  
  22. }  
View Code
  1. @using MvcViewDataViewBagTempData_Demo.Models;  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h3>@ViewBag.Heading</h3>  
  8. <table class="table table-bordered">  
  9.     <thead>  
  10.         <tr>  
  11.             <th>Id</th>  
  12.             <th>Name</th>  
  13.             <th>Gender</th>  
  14.             <th>Age</th>  
  15.             <th>Position</th>  
  16.             <th>Office</th>  
  17.             <th>Salary</th>  
  18.         </tr>  
  19.     </thead>  
  20.     <tbody>  
  21.         @foreach (var emp in (ViewBag.Employee as List<Employee>))  
  22.         {  
  23.             <tr>  
  24.                 <td>@emp.Id</td>  
  25.                 <td>@emp.Name</td>  
  26.                 <td>@emp.Gender</td>  
  27.                 <td>@emp.Age</td>  
  28.                 <td>@emp.Position</td>  
  29.                 <td>@emp.Office</td>  
  30.                 <td>@emp.Salary</td>  
  31.             </tr>  
  32.         }  
  33.     </tbody>  
  34. </table>  
TempData Controller Code
  1. using MvcViewDataViewBagTempData_Demo.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 MvcViewDataViewBagTempData_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext = new EmployeeContext();  
  13.   
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             TempData["Employee"] = employee;  
  18.             TempData["Heading"]= "List of Employee";  
  19.             return View();  
  20.         }  
  21.     }  
  22. }  
View Code
  1. @using MvcViewDataViewBagTempData_Demo.Models;  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h3>@TempData["Heading"]</h3>  
  8. <table class="table table-bordered">  
  9.     <thead>  
  10.         <tr>  
  11.             <th>Id</th>  
  12.             <th>Name</th>  
  13.             <th>Gender</th>  
  14.             <th>Age</th>  
  15.             <th>Position</th>  
  16.             <th>Office</th>  
  17.             <th>Salary</th>  
  18.         </tr>  
  19.     </thead>  
  20.     <tbody>  
  21.         @foreach (var emp in (TempData["Employee"] as List<Employee>))  
  22.         {  
  23.             <tr>  
  24.                 <td>@emp.Id</td>  
  25.                 <td>@emp.Name</td>  
  26.                 <td>@emp.Gender</td>  
  27.                 <td>@emp.Age</td>  
  28.                 <td>@emp.Position</td>  
  29.                 <td>@emp.Office</td>  
  30.                 <td>@emp.Salary</td>  
  31.             </tr>  
  32.         }  
  33.     </tbody>  
  34. </table>  
Step 8
 
Build and run your project ctr+F5
 
Learn About ViewData, ViewBag And TempData In ASP.NET MVC