ExpandoObject, anonymous types and Razor

前端 未结 4 1621
北恋
北恋 2021-01-03 04:16

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

ExpandoObject o          


        
4条回答
  •  春和景丽
    2021-01-03 04:32

    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
    

提交回复
热议问题