ExpandoObject, anonymous types and Razor

kenwarner picture kenwarner · Jun 24, 2011 · Viewed 8.5k times · Source

I want to use an ExpandoObject as the viewmodel for a Razor view of type ViewPage<dynamic>. I get an error when I do this

ExpandoObject o = new ExpandoObject();
o.stuff = new { Foo = "bar" };
return View(o);

what can I do to make this work?

Answer

gram picture gram · Jun 24, 2011

You can do it with the extension method mentioned in this question:

Dynamic Anonymous type in Razor causes RuntimeBinderException

So your controller code would look like:

dynamic o = new ExpandoObject();
o.Stuff = new { Foo = "Bar" }.ToExpando();

return View(o);

And then your view:

@model dynamic

@Model.Stuff.Bar