ExpandoObject, anonymous types and Razor

纵饮孤独 提交于 2019-11-30 15:42:45
gram

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

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);

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; }
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!