Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpandoObject, anonymous types and Razor

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?

like image 629
kenwarner Avatar asked Jun 24 '11 14:06

kenwarner


1 Answers

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
like image 117
gram Avatar answered Oct 30 '22 02:10

gram