ExpandoObject, anonymous types and Razor

前端 未结 4 1631
北恋
北恋 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:34

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

提交回复
热议问题