Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to access a .NET MVC ViewBag's properties using a string key?

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?

like image 335
Richard Garside Avatar asked Feb 24 '11 16:02

Richard Garside


People also ask

Can ViewData be accessed via the ViewBag property?

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.

How do I access model controller?

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.

How do I get ViewBag data in Cshtml?

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.


1 Answers

Use ViewData[theKey]. Both ViewData and ViewBag use the same underlying storage.

like image 145
marcind Avatar answered Oct 01 '22 13:10

marcind