RazorEngine 使用匿名对象 RuntimeBinderException [英] RazorEngine using anonymous objects RuntimeBinderException

查看:52
本文介绍了RazorEngine 使用匿名对象 RuntimeBinderException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模板解决方案中使用 RazorEngine.我必须为我的模型数据使用匿名对象.代码:

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

我收到 RuntimeBinderException(对象"不包含名称"的定义).

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

有人可以帮我吗?

谢谢!

推荐答案

在我看来,具有内部属性的匿名类型是一个糟糕的 .NET 框架设计决策.

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

这是解决此问题的快速且不错的扩展,即将匿名对象立即转换为 ExpandoObject.

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

请参考这个问题的回答:https://stackoverflow.com/a/5670899/544283.

这篇关于RazorEngine 使用匿名对象 RuntimeBinderException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆