Ivan-Mark Debono Ivan-Mark Debono - 2 months ago 30
C# Question

How to iterate through a list in a view using RazorEngine?

I'm using

RazorEngine
to render views within a WebApi project. I have the following code to iterate through a list of items:

@using System.Collections.Generic;

@using MyApp;

@Model IEnumerable<Customer>

@foreach (var item in Model)
{
<tr>
<td>
item.Name
</td>
</tr>
}


However, I get an exception:


Cannot implicitly convert type 'RazorEngine.Compilation.RazorDynamicObject' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)


What is the correct way to iterate through a list using
RazorEngine
?

Answer

Change

@Model IEnumerable<Customer>

to

@model IEnumerable<Customer>

It's case sensitive, when declaring the model type you should use lower case. Then you should be able to correctly iterate over your model.

Also, you should change item.Name to be @item.Name since you are referring to a variable and don't just want a literal string.

I created an MCVE with RazorEngine 3.9.0 to verify that it worked for me.

using System;
using System.Collections.Generic;
using RazorEngine;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var template = @"
@using System.Collections.Generic;
@using MyApp;
@model IEnumerable<Customer>

@foreach (var item in Model)
{
    <tr>
        <td>
            @item.Name
        </td>
    </tr>
}
";

            var result = Razor.Parse(template, new List<Customer>
                        { new Customer { Name = "Hello World" } });
            Console.WriteLine(result);
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }

    public class Customer
    {
        public string Name { get; set; }
    }
}
Comments