How to access Viewbag in Javascript code


  1. ViewBag is used to send data from controller to view. 
  2. On view it is very easy to access the ViewBag.
  3. In this tutorial we will see how to access ViewBag inside script tag.

Example :

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.

View :


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.

UI :


The ViewBag text is fetched and assign to h2 element. The above screenshot shows how ViewBag value looks in debugging mode.


0 comments:

Post a Comment