Storing an Anonymous Object in ViewBag

one.beat.consumer picture one.beat.consumer · Jan 24, 2012 · Viewed 10k times · Source

This is probably a silly question, but I am trying to stuff an anonymous object in ViewBag like so:

ViewBag.Stuff = new { Name = "Test", Email = "[email protected]" };

and access it from a View like so:

@ViewBag.Stuff.Name

I understand ViewBag is dynamic and that "Stuff" is an anonymous object... but when I look with the debugger from the View line above, I can see all the properties with the proper values. Why does the model binder have such a hard time with this?

Is there a good way to accomplish this without creating a model class? I want to continue using new {}

Answer

SoWeLie picture SoWeLie · Jan 24, 2012

Essentially the issue is that anonymous types are generated as internal (see answer), making hard typed references to the object's property impossible from the View. This article provides a more detailed explanation:

http://www.heartysoft.com/anonymous-types-c-sharp-4-dynamic

It is possible to accomplish with the use of a Dynamic Anonymous wrapper class (@Dakill's answer), but gets ugly fast and should make a programmer question why he/she would do so.