ASP.NET MVC ViewData, ViewBag and TempData
ASP.NET MVC provides three variables to store and passing values from controller to view. Both ViewData and ViewBag are similar except TempData that has additional features.
We will discuss about each of these with example.
ASP.NET MVC ViewData
It is a dictionary of objects and derived from ViewDataDictionary class. We can access value by using string as a key. It is type-safe and requires typecasting for data type. It avoids error and check for null reference at run time. It is accessible only during current request.
Example
We are creating a controller and returning a view to the browser. This controller passes Courses ViewData to the view.
Controller
View
// Index.cshtml
Output:
It produces the following output to the browser.
ASP.NET MVC ViewBag
It is a dynamic property which is similar to ViewData. It was introduced in .NET Framework version 4.0. it is used to send data from controller to the view page. ViewBag can get and set value dynamically that’s why it is called dynamic property. It does not require type conversion and convert type dynamically.
Example
Here, in this example, we are implementing ViewBag property. Controller and an Index file is given below.
Controller
View
Output:
The Index file produces the following output to the browser.
ASP.NET MVC TempData
It represents a set of data that persists only from one request to the next. It is derived from TempDataDictionary, we can use its object to pass data as we did in ViewData. The value of TempData persists only from one request to the next. Retention is used to mark key to persist data so that it can retain for the next request.
We can also use TempData to pass data from one action to another action. Let’s see an example.
Example
Controller
// TempDataController.cs
View
// Index.cshtml
Output:
This index file produces the following output to the browser.