What are ViewData, ViewBag, and TempData in ASP.NET MVC?

Dhananjay Kumar / Friday, November 6, 2015

 

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 scenarios. You may have a requirement to pass data in the following cases:

·        Pass data from the 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 the 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:

public ActionResult Index()
        {
            List<Product> p = new List<Product>() {
 
               new Product { Id = 1, Name = "Pen", Price = 300 },
               new Product { 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:

<table class="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 a 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:

public ActionResult 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:

 
public ActionResult 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 a 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 the 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 the 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 for null checking.

·        Life of ViewBag is restricted to the current request and becomes Null on redirection.

·        ViewBag is a 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 the controller to view in a single cycle. The value assigned in ViewBag and ViewData get nullified in the next HTPP request or navigating to another 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 another 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 assign a value to TempData as shown in the listing below:

  public ActionResult 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:

public string 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 are 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 the 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!