I have a value that I've put in the ViewBag:
ViewBag.SomeKey = value;
In my view I have the key stored as a String.
String theKey = "SomeKey";
Is there a way to access my value from the Viewbag using this String version of the key?
To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.
In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.
cshtml view, you can access ViewBag. TotalStudents property, as shown below. Internally, ViewBag is a wrapper around ViewData. It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.
Use ViewData[theKey]
. Both ViewData
and ViewBag
use the same underlying storage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With