I have often seen entry level developers struggle with the differences between and usage of ViewData, ViewBag and TempData in ASP.NET MVC. And while there are many articles and blog posts on this topic out there, I’ll try to explain it simply.
To start with, ViewData, ViewBag, and TempData all three are objects in ASP.NET MVC that are used to carry or pass data in different scenario. You may have a requirement to pass data in the following cases:
· Pass data from controller to view;
· Pass data from one controller to another controller;
· Pass data from one action to another action;
· Pass data between subsequent HTTP requests
At a higher level, we can depict the use of ViewData, ViewBag, and TempData as shown in the image below:
Passing Data from Controller to View
Let us consider a scenario where you’re passing data from controller to view. Usually we pass complex data to the view using the model. Here let’s say we have a strongly typed View which is using the data model List as shown in the listing below:
publicActionResult Index()
{
List<Product> p = newList<Product>() {
newProduct { Id = 1, Name = "Pen", Price = 300 },
newProduct { Id = 2, Name = "Pencil", Price = 100 }
};
return View(p);
}
On the View, data is displayed by rendering the model as shown in the listing below:
<tableclass="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
th>
<th>
@Html.DisplayNameFor(model => model.Price)
th>
<th>th>
tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
td>
<td>
@Html.DisplayFor(modelItem => item.Price)
td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
td>
tr>
}
table>
Now we have a requirement to pass data (other than model) to the view from the controller. There are two possible ways data can be passed.
Let us assume that we want to pass a simple string to the view besides the Product data model.
Passing data using ViewBag
We can pass data using the ViewBag as shown in the listing below:
publicActionResult Index()
{
ViewBag.data1 = "I am ViewBag data";
return View(p);
}
On the view, ViewBag data can be read as the property of the ViewBag as shown in the listing below:
<h2>@ViewBag.data1h2>
Passing data using ViewData
We can pass data using the ViewData as shown in the listing below:
publicActionResult Index()
{
ViewData["data1"] = "I am ViewBag data";
return View(p);
}
On the view, ViewData data can be read as the string value pair of the ViewData as shown in the listing below:
<h2>@ViewData["data1"]h2>
Let us examine the differences between ViewData and ViewBag. ViewBag is a dynamic property which is based on the dynamic type, whereas ViewData is a dictionary object. We can read data from ViewBag as a property and from ViewData as key- value pair. Some bullet points about both are as follows:
ViewData
· It’s a property of type ViewDataDictionary class.
· Data can be passed in the form of a key-value pair.
· To read the complex type data on the view, typecasting is required.
· To avoid exception, null checking is required.
· Life of ViewData is restricted to the current request and becomes Null on redirection.
· ViewData is a property of the ControllerBase class
ViewBag
· It’s a property of dynamic type.
· Data is passed as a property of the object.
· There is no need of typecasting to read the data.
· There is no need of null checking.
· Life of ViewBag is restricted to the current request and becomes Null on redirection.
· ViewBag is property of ControllerBase class.
In the ControllerBase class, both are defined as property as shown in the image below:
We can summarize ViewBag and ViewData as objects that are used to pass data from controller to view in a single cycle. Value assigned in ViewBag and ViewData get nullified in the next HTPP request or navigating to other view.
TempData
One of the major attributes of both ViewData and ViewBag are that their lifecycle is limited to one HTTP request. On redirection, they lose the data. We may have other scenario to pass data from one HTTP request to the next HTTP request; for example, passing data from one controller to another controller or one action to other action. TempData is used to pass data from one request to the next request.
Let us say that we want to navigate to Read action from Index action and while navigating, pass data to the Read action from the Index action. So in the Index action, we can assigne value to TempData as shown in the listing below:
publicActionResult Index()
{
TempData["data1"] = "I am from different action";
return RedirectToAction("Read");
}
We can read TempData as a key-value pair. In the Read action, TempData can be read as shown in the listing below:
publicstring Read()
{
string str;
str = TempData["data1"].ToString();
return str;
}
Like ViewData, TempData is also a dictionary object and to read the data, typecasting and null checking is required. Keep in mind that TempData can persist data only to the subsequent HTTP request. When you are very sure about the redirection, then use TempData to pass the data.
Some points about TempData are as follows:
· TempData is used to pass data from one HTTP request to next HTTP request.
o In other words, TempData is used to pass data from one controller to another controller or action to another action.
· TempData is a property of BaseController class.
· TempData stores data in a session object
· TempData is a property of ControllerBase class
· To read data, Typecasting and null checking is required.
· Type of TempData is TempDataDictionary.
· TempData works with HTTP redirection like HTTP 302/303 status code
Summary
ViewData, ViewBag, and TempData are used to pass data between controller, action, and views. To pass data from controller to view, either ViewData or ViewBag can be used. To pass data from one controller to another controller, TempData can be used.
I hope now the concepts of ViewBag, ViewData and TempData are a bit clearer – and thanks for reading!
Try our jQuery HTML5 controls for your web apps and take immediate advantage of their stunning capabilities. Download Free Trial now!