如何使用HTML帮手泛型集合? [英] How to use html helper for a generic collection?
问题描述
我有一个强类型来看,它是一个IEnumerable。我试图用DisplayFor帮手集合,它是我的模型的属性。迭代我的模型当帮手完美的作品,但是当我尝试使用它的一个子集,它崩溃。
我第一次尝试在写这样的:
@ Html.DisplayFor(modelItem =>
item.Months.Where(X => x.Equals(月))选择(X => x.Amount)。)
但后来我得到这个运行时错误:模板只能与现场访问,访问属性,一维数组的索引,或单参数自定义索引前pressions用
这是我的看法的code:
@foreach(以型号VAR项)
{
&所述; TR>
&所述; TD>
@ Html.DisplayFor(modelItem => item.Name)@ *它完美这里@ *
< / TD> @foreach(VAR月item.Months)
{
&所述; TD>
@ month.Amount @ *我如何使用DisplayFor帮手吗? * @
< / TD>
} < / TR>
}
这是我的模型的code:
公共类系
{
公共字符串名称{;组; }
公开名单<&月份GT; {月获得;组; }
}公共类月
{
公众诠释号{搞定;组; }
[数据类型(DataType.Currency)
公共小数金额{搞定;组; }
}
您应该考虑使用部分景色
。
@ Html.Partial(_个月,月)
那么你的部分观点可能是类似如下:
@model IEnumerable的<&月份GT;<表>
&所述; TR>
<第i个
@ Html.DisplayNameFor(型号=> model.number)
< /第i
<第i个
@ Html.DisplayNameFor(型号=> model.Amount)
< /第i
< / TR>@foreach(以型号VAR项){
&所述; TR>
&所述; TD>
@ Html.DisplayFor(modelItem => item.number)
< / TD>
&所述; TD>
@ Html.DisplayFor(modelItem => item.Amount)
< / TD>
< / TR>
}< /表>
I have a strongly typed view, it is an IEnumerable. I am trying to use the DisplayFor helper for a collection, which is a property of my model. The helper works perfectly when iterating my model, but when I try to use it for a sub collection, it crashes.
My first attempt was writing something like this:
@Html.DisplayFor(modelItem =>
item.Months.Where(x=>x.Equals(month)).Select(x=>x.Amount))
But then I got this run-time error: "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."
That is my View's Code:
@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>
}
That is my Model's Code:
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; }
}
You should consider using Partial Views
.
@Html.Partial("_months", Months)
Then your partial view could be something like below:
@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>
这篇关于如何使用HTML帮手泛型集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!