In ASP.NET MVC the property ViewBag is of type dynamic.
Throught the code, various “properties” of ViewBag are assigned to:
ViewBag.Message = "Hello world";
ViewBag.Title = "Page title";
How does this work? From reading the docs I get that ViewBag itself can by anything, but why (or how) does assigning something to a “member” of dynamic type work?
Here is how ViewBag is defined in public abstract class ControllerBase : IController class:
[Dynamic]
public dynamic ViewBag { get; }
//
// Summary:
// Gets or sets the dictionary for view data.
//
// Returns:
// The dictionary for the view data.
public ViewDataDictionary ViewData { get; set; }
Just curious.
Relevant question: Where can I find the official documentation for DynamicViewDataDictionary?
ViewBagis anExpandoObjector something similar. This is basically just a glorified Dictionary with the “properties” being the keys.UPDATE:
Actually, it is a
DynamicViewDataDictionary, a class internal to the ASP.NET MVC source code. This class inherits fromDynamicObjectand simply is a wrapper around aViewDataDictionary, in case of theViewBagaround theViewDataproperty ofControllerBase.As you can see in
TryGetMemberandTrySetMemberthe calls are delegated to theViewDatawithout any logic.