ViewBag is defined as to pass data from Controller Action to view to render the data that is being passed. Now we can pass data between
Controller Action and View either by using
ViewBag or ViewData.
ViewBag: It is type of Dynamic object, which means we can add new fields to viewbag dynamically and access these fields in the View. We need to initialize the object of viewbag at the time of creating new fields.
Nishi Tiwari
27-Jan-2020ViewBag is defined as to pass data from Controller Action to view to render the data that is being passed. Now we can pass data between Controller Action and View either by using ViewBag or ViewData.
ViewBag: It is type of Dynamic object, which means we can add new fields to viewbag dynamically and access these fields in the View. We need to initialize the object of viewbag at the time of creating new fields.
e.g: 1. Creating ViewBag: ViewBag.FirstName="John";
2. Accessing View: @ViewBag.FirstName.
Example
In this example, we are implementing ViewBag property.
Controller
View
Output:
The Index file produces the following output to the browser.