如何使用 RazorEngine 遍历视图中的列表?
How to iterate through a list in a view using RazorEngine?
我正在使用 RazorEngine
在 WebApi 项目中呈现视图。我有以下代码来遍历项目列表:
@using System.Collections.Generic;
@using MyApp;
@Model IEnumerable<Customer>
@foreach (var item in Model)
{
<tr>
<td>
item.Name
</td>
</tr>
}
但是,我得到一个例外:
Cannot implicitly convert type 'RazorEngine.Compilation.RazorDynamicObject' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)
使用 RazorEngine
遍历列表的正确方法是什么?
改变
@Model IEnumerable<Customer>
至
@model IEnumerable<Customer>
区分大小写,声明模型类型时应使用小写。然后你应该能够正确地迭代你的模型。
此外,您应该将 item.Name
更改为 @item.Name
,因为您指的是一个变量,而不只是想要一个文字字符串。
我用 RazorEngine 3.9.0 创建了一个 MCVE 来验证它是否适合我。
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; }
}
}
我正在使用 RazorEngine
在 WebApi 项目中呈现视图。我有以下代码来遍历项目列表:
@using System.Collections.Generic;
@using MyApp;
@Model IEnumerable<Customer>
@foreach (var item in Model)
{
<tr>
<td>
item.Name
</td>
</tr>
}
但是,我得到一个例外:
Cannot implicitly convert type 'RazorEngine.Compilation.RazorDynamicObject' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)
使用 RazorEngine
遍历列表的正确方法是什么?
改变
@Model IEnumerable<Customer>
至
@model IEnumerable<Customer>
区分大小写,声明模型类型时应使用小写。然后你应该能够正确地迭代你的模型。
此外,您应该将 item.Name
更改为 @item.Name
,因为您指的是一个变量,而不只是想要一个文字字符串。
我用 RazorEngine 3.9.0 创建了一个 MCVE 来验证它是否适合我。
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; }
}
}