ExpandoObject, anonymous types and Razor

2019-02-10 23:19发布

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?

4条回答
Melony?
2楼-- · 2019-02-10 23:55

I stand corrected, @gram has the right idea. However, this is still one way to modify your concept.

Edit

You have to give .stuff a type since dynamic must know what type of object(s) it's dealing with.

.stuff becomes internal when you set it to an anonymous type, so @model dynamic won't help you here

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

And, of course, the MyTypedObject:

public class MyTypedObject
{
    public string Foo { get; set; }
}
查看更多
可以哭但决不认输i
3楼-- · 2019-02-11 00:04

Try setting the type as dynamic

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

Go through this excellent post on ExpandoObject

查看更多
beautiful°
4楼-- · 2019-02-11 00:06

Using the open source Dynamitey (in nuget) you could make a graph of ExpandoObjects with a very clean syntax;

  dynamic Expando = Build<ExpandoObject>.NewObject;

  var o = Expando (
      stuff: Expando(foo:"bar")
  );

  return View(o);
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-02-11 00:11

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
查看更多
登录 后发表回答