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
- ViewData is a dictionary object that is derived from ViewDataDictionary class.
- ViewData is a property of ControllerBase class.
- ViewData is used to pass data from controller to corresponding view.
- Its life lies only during the current request.
- If redirection occurs then its value becomes null.
- Its required typecasting for getting data and checking for null values to avoid error.
ViewBag
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
- Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
- ViewBag is a property of ControllerBase class.
- Its life also lies only during the current request.
- If redirection occurs then its value becomes null.
- It doesn’t required typecasting for getting data.
TempData
- TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
- TempData is a property of ControllerBase class.
- TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
- Its life is very short and lies only till the target view is fully loaded.
- It’s required typecasting for getting data and check for null values to avoid error.
- 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.
- create table Employee
- (
- Id int primary key identity(1,1),
- Name nvarchar(50),
- Gender char(10),
- Age int,
- Position nvarchar(50),
- Office nvarchar(50),
- Salary int
- )
-
- insert into Employee values('Arvind Kumar','Male',30,'Software Developer','Bangalore',55000)
- insert into Employee values('Divya','Female',25,'Designer','Bangalore',50000)
- insert into Employee values('Rahul Sharma','Male',28,'UI Developer','Bangalore',45000)
- insert into Employee values('Monica','Female',35,'Angular Developer','Bangalore',60000)
- 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.
Step 4
Select "empty" template, check on the MVC box, and click OK.
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"
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".
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
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".
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".
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
Entity Framework gets added and the respective class gets generated under the Models folder.
Step 6
Right-click on Controllers folder and add a controller.
A window will appear. Choose MVC5 Controller-Empty and click "Add".
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.
Controller code
- using MvcViewDataViewBagTempData_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcViewDataViewBagTempData_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext = new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- ViewData["Employee"] = employee;
- ViewData["Heading"]= "List of Employee";
- return View();
- }
- }
- }
Step 7
Right click on index action method of HomeController.
- @using MvcViewDataViewBagTempData_Demo.Models;
-
- @{
- ViewBag.Title = "Index";
- }
-
- <h3>@ViewData["Heading"]</h3>
- <table class="table table-bordered">
- <thead>
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Gender</th>
- <th>Age</th>
- <th>Position</th>
- <th>Office</th>
- <th>Salary</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var emp in (ViewData["Employee"] as List<Employee>))
- {
- <tr>
- <td>@emp.Id</td>
- <td>@emp.Name</td>
- <td>@emp.Gender</td>
- <td>@emp.Age</td>
- <td>@emp.Position</td>
- <td>@emp.Office</td>
- <td>@emp.Salary</td>
- </tr>
- }
- </tbody>
- </table>
ViewBag Controller Code
- using MvcViewDataViewBagTempData_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcViewDataViewBagTempData_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext = new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- ViewBag.Employee = employee;
- ViewBag.Heading = "List of Employee";
- return View();
- }
- }
- }
View Code
- @using MvcViewDataViewBagTempData_Demo.Models;
-
- @{
- ViewBag.Title = "Index";
- }
-
- <h3>@ViewBag.Heading</h3>
- <table class="table table-bordered">
- <thead>
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Gender</th>
- <th>Age</th>
- <th>Position</th>
- <th>Office</th>
- <th>Salary</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var emp in (ViewBag.Employee as List<Employee>))
- {
- <tr>
- <td>@emp.Id</td>
- <td>@emp.Name</td>
- <td>@emp.Gender</td>
- <td>@emp.Age</td>
- <td>@emp.Position</td>
- <td>@emp.Office</td>
- <td>@emp.Salary</td>
- </tr>
- }
- </tbody>
- </table>
TempData Controller Code
- using MvcViewDataViewBagTempData_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcViewDataViewBagTempData_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext = new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- TempData["Employee"] = employee;
- TempData["Heading"]= "List of Employee";
- return View();
- }
- }
- }
View Code
- @using MvcViewDataViewBagTempData_Demo.Models;
-
- @{
- ViewBag.Title = "Index";
- }
-
- <h3>@TempData["Heading"]</h3>
- <table class="table table-bordered">
- <thead>
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Gender</th>
- <th>Age</th>
- <th>Position</th>
- <th>Office</th>
- <th>Salary</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var emp in (TempData["Employee"] as List<Employee>))
- {
- <tr>
- <td>@emp.Id</td>
- <td>@emp.Name</td>
- <td>@emp.Gender</td>
- <td>@emp.Age</td>
- <td>@emp.Position</td>
- <td>@emp.Office</td>
- <td>@emp.Salary</td>
- </tr>
- }
- </tbody>
- </table>
Step 8
Build and run your project ctr+F5