RazorEngine using anonymous objects RuntimeBinderException

不羁的心 提交于 2020-01-14 06:45:41

问题


I'm using RazorEngine in a templating solution. I have to use anonymous objects for my model data. The code:

        string template = @"
            Name: @Model.name
            @foreach(var person in @Model.People) {
                <row>
                    <column header=""Name"" width=""5cm"">@person.Name</column>
                    <column header=""Age"" width=""5cm"">@person.Age</column>
                </row>
            }";

        var personList = new List<object>();
        personList.Add(new { Name = "Bob", Age = 25 });
        personList.Add(new { Name = "Peter", Age = 30 });

        var model = new { name = "Henry", People = personList };

        string result = Razor.Parse(template, model);  

I'm getting an RuntimeBinderException ('object' does not contain a definition for 'Name').

Can anyone help me?

Thank you!


回答1:


Anonymous types having internal properties is a poor .NET framework design decision, in my opinion.

Here is a quick and nice extension to fix this problem i.e. by converting the anonymous object into an ExpandoObject right away.

Please refer to this question's answer: https://stackoverflow.com/a/5670899/544283.



来源:https://stackoverflow.com/questions/16737760/razorengine-using-anonymous-objects-runtimebinderexception

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