0

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!

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • 1
    Have you tried using the `dynamic` type since the anonymous type is generated as internal, so the binder doesn't really "know" about it as such: `dynamic personList = new List(); ... dynamic model = new { name = "Henry", People = personList };` – chridam May 24 '13 at 14:54

1 Answers1

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.

Community
  • 1
  • 1
Esteban
  • 3,108
  • 3
  • 32
  • 51