ViewData, ViewBag, And TempData In ASP.NET MVC

Introduction

In this article, I will explain about ViewData, ViewBag, and TempData while working in MVC. ASP.NET MVC provides quite a few ways of transferring the data from Controller to View.

  1. ViewBag
  2. ViewData
  3. Tempdata

ViewBag

ViewBag transfers the data from the Controller to the View.

  • The lifespan of the ViewBag starts and ends in the current request only. 
  • We can assign any number of properties and values to ViewBag.
  • If it redirects, then its value becomes null.
  • It is the dynamic object to pass the data from Controller to View.
General Form

ViewBag.PropertyName = value/Object/List;

Example Write code in Controller

ViewBag.Name = “Chetan Nargund”;

ViewBag Example

Write the following code in Controller.

ViewBag

Retrieve ViewBag Value in the View (Write the code in View)

ViewBag

Note

PropertyName must be the same on both the sides - Controller and View. (Here, PropertyName: Name)

Output

Chetan Nargund

ViewBag

ViewData

ViewData transfers data from the Controller to the View.
  • We can assign any number of properties and values to ViewData.
  • Dictionary objects are needed to pass the data from Controller to the View.
  • Life of ViewData is restricted to the current request and becomes NULL on redirection.
General Form

ViewData[“KeyName”] = value/Object/List;

Example: Write code in Controller

ViewData[“Name”] = “Chetan Nargund”;

ViewData Example

Write this code in Controller.

ViewBag

Retrieve ViewData Value in the View (Write this code in View):

ViewBag

Output

Chetan Nargund

ViewBag

TempData

TempData transfers data from the Controller to the View.
  • We can assign any number of properties and values to TempData.
  • TempData can also be used to transfer Model and List from Controller to View.
  • TempData works with HTTP redirection.
  • TempData is used to pass data between two consecutive requests.
General Form

TempData[“KeyName”] = value/Object/List;

Example Write code in Controller

TempData[“Name”] = “Chetan Nargund”;

TempData Example

Write this code in Controller.

ViewBag

Retrieve TempData Value in the View (Write this code in View).

ViewBag

Output

Chetan Nargund

ViewBag
Why Use TempData when we have ViewBag and ViewData?

One of the major disadvantages of both ViewData and ViewBag is that the lifecycle is limited  to one HTTP request. On redirection, they lose the data. On the other hand, TempData is used to pass the data from one request to the next request. TempData helps to maintain data between those redirects. It internally uses session variables.

I hope that now the concept of ViewBag, ViewData, and TempData is a bit more clear. Thanks for reading.

 

Up Next
    Ebook Download
    View all
    Learn
    View all