我有一个强类型 View ,它是一个 IEnumerable。我正在尝试将 DisplayFor 助手用于集合,这是我模型的一个属性。在迭代我的模型时,助手工作得很好,但是当我尝试将它用于子集合时,它崩溃了。
我的第一次尝试是写这样的东西:
@Html.DisplayFor(modelItem =>
item.Months.Where(x=>x.Equals(month)).Select(x=>x.Amount))
但随后我遇到了这个运行时错误:“模板只能用于字段访问、属性访问、一维数组索引或单参数自定义索引器表达式。”
这是我的 View 代码:
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name) @* It works perfectly here*@
</td>
@foreach (var month in item.Months)
{
<td>
@month.Amount @* How can I use DisplayFor helper here ? *@
</td>
}
</tr>
}
这是我模型的代码:
public class Department
{
public string Name { get; set; }
public List<Month> Months { get; set; }
}
public class Month
{
public int number { get; set; }
[DataType(DataType.Currency)]
public decimal Amount { get; set; }
}
最佳答案
您应该考虑使用部分 View
。
@Html.Partial("_months", Months)
那么你的部分 View 可能如下所示:
@model IEnumerable<Months>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.number)
</th>
<th>
@Html.DisplayNameFor(model => model.Amount)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.number)
</td>
<td>
@Html.DisplayFor(modelItem => item.Amount)
</td>
</tr>
}
</table>
关于c# - 如何将 html 助手用于通用集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19316769/