- ViewBag is used to send data from controller to view.
- On view it is very easy to access the ViewBag.
- In this tutorial we will see how to access ViewBag inside script tag.
We will create a ViewBag and inside Action method as shown below.
In the above screenshot, we have created a ViewBag with key Car inside Index action method. We will access this ViewBag when view will render.
On View we have created a h2 element. We have accessed the ViewBag inside script element using @ sign used inside single quotes. Then the ViewBag value is assigned to h2 element using html method in jQuery.
The ViewBag text is fetched and assign to h2 element. The above screenshot shows how ViewBag value looks in debugging mode.