Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How ViewBag in ASP.NET MVC works

How does the ASP.NET MVC's ViewBag work? MSDN says it is just an Object, which intrigues me, how does "Magic" properties such as ViewBag.Foo and magic strings ViewBag["Hello"] actually work?

Also, how can I make one and use it in my ASP.NET WebForms app?

Examples would be really appreciated!

like image 760
Aniket Inge Avatar asked Feb 15 '13 13:02

Aniket Inge


People also ask

How do you use ViewBag in view?

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 dynamic is ViewBag?

ViewBag is a dynamic type that allow you to dynamically set or get values and allow you to add any number of additional fields without a strongly-typed class They allow you to pass data from controller to view.


2 Answers

ViewBag is of type dynamic but, is internally an System.Dynamic.ExpandoObject()

It is declared like this:

dynamic ViewBag = new System.Dynamic.ExpandoObject();

which is why you can do :

ViewBag.Foo = "Bar";

A Sample Expander Object Code:

public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider {     public Dictionary<string, object> objectDictionary;      public ExpanderObject()     {         objectDictionary = new Dictionary<string, object>();     }     public override bool TryGetMember(GetMemberBinder binder, out object result)     {         object val;         if (objectDictionary.TryGetValue(binder.Name, out val))         {             result = val;             return true;         }         result = null;         return false;     }      public override bool TrySetMember(SetMemberBinder binder, object value)     {         try         {             objectDictionary[binder.Name] = value;             return true;         }         catch (Exception ex)         {             return false;         }     } } 
like image 116
Aniket Inge Avatar answered Oct 07 '22 14:10

Aniket Inge


It's a dynamic object, meaning you can add properties to it in the controller, and read them later in the view, because you are essentially creating the object as you do, a feature of the dynamic type. See this MSDN article on dynamics. See this article on it's usage in relation to MVC.

If you wanted to use this for web forms, add a dynamic property to a base page class like so:

public class BasePage : Page {      public dynamic ViewBagProperty     {         get;         set;     } } 

Have all of your pages inherit from this. You should be able to, in your ASP.NET markup, do:

<%= ViewBagProperty.X %> 

That should work. If not, there are ways to work around it.

like image 30
Brian Mains Avatar answered Oct 07 '22 15:10

Brian Mains