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.
- ViewBag
- ViewData
- 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 passes the data from the Controller to the View.
General Form
ViewBag.PropertyName = value/Object/List;
Example. Write code in the Controller
ViewBag.Name = "Chetan Nargund";
ViewBag
Example. Write the following code in Controller.
Retrieve ViewBag Value in the View (Write the code in View).
Note. PropertyName must be the same on both sides - Controller and View. (Here, PropertyName: Name).
Output
Chetan Nargund
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 the 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 the Controller.
ViewData["KeyName"] = value/Object/List;
ViewData
Example. Write this code in Controller.
Retrieve ViewData Value in the View (Write this code in View).
Output
Chetan Nargund
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 the Controller
TempData["Name"] = "Chetan Nargund";
TempData
Example. Write this code in Controller.
Retrieve TempData Value in the View (Write this code in View).
Output
Chetan Nargund
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 concepts of ViewBag, ViewData, and TempData is a bit more clear. Thanks for reading.