The ViewBag is a DynamicViewDataDictionary, which inherits DynamicObject
. Getting the keys is straightforward using "GetDynamicMemberNames", but getting the values is slightly more verbose. The following converts the ViewBag to a dictionary (shamelessly plagiarized borrowed from Aaronaught's answer here):
var values = new Dictionary<string, object>();
IEnumerable<string> keys = ViewBag.GetDynamicMemberNames();
foreach (string key in keys)
{
var binder = Microsoft.CSharp.RuntimeBinder.Binder.GetMember(
CSharpBinderFlags.None, key,
ViewBag.GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
var callsite = CallSite<Func<CallSite, object, object>>.Create(binder);
var val = callsite.Target(callsite, ViewBag);
values.Add(key, val);
}
I feel like scrapping Viewbag entirely.
This sounds like a good idea -- far better to use strongly-typed view models, where possible.