ASP.NET Core 5.0 View Bag View Data Temp Data Edit

Murugan Andezuthu Dharmaratnam | 18 January 2021 | 113

There are three different ways of returning the data from Controller to View or .cshtml file.

ViewData

ViewData is used for returning the data from Controller's action method to View or .cshtml file. ViewData is a dictionary or it's a property with get & set accessors, which is part of ControllerBase class. ViewDataDictionary class inherits from IDictionary interface and ViewData returns ViewDataDictionary class object, that means ViewData is a collection of Dictionary objects with string, object types. ViewData's data can be accessed in the current page instance. If there is any navigation from one view to another view then there may be chances of losing the data from ViewData object.

ViewBag

ViewBag is used for returning the data from Controller to View. ViewBag is a property with only get accessor which is a member of ControllerBase abstract class with dynamic type. It is similar to ViewData. ViewBag object data can be accessed in the current page instance. If there is any navigation from one view to another view then there may be chances of losing the data from ViewBag object.

TempData

Using TempData we can pass the data from Controller's Action Method to View or .cshtml file. It is similar to ViewData. TempData is a dictionary of objects or a property with get and set accessors which is a member of ControllerBase abstract class. TempData has a return type TempDataDictionary class and TempDataDictionary class inherits from IDictionary interface that means TempData is a collection of Dictionary object with string, object types. Whenever there is any navigation from one View to another View, TempData object's data will be available and can be accessed in redirection of pages. It is different from ViewData and ViewBag, In ViewData and ViewBag whenever there is any navigation or redirection of webpage then the data will not be available. But the data will be available even during the redirection of webpages in TempData.