【问题标题】:How to use html helper for a generic collection?如何将 html 助手用于通用集合?
【发布时间】:2013-11-24 17:36:07
【问题描述】:

我有一个强类型视图,它是一个 IEnumerable。我正在尝试将 DisplayFor 帮助器用于集合,这是我模型的属性。迭代我的模型时,助手工作得很好,但是当我尝试将它用于子集合时,它会崩溃。

我的第一次尝试是这样写的:

@Html.DisplayFor(modelItem =>
item.Months.Where(x=>x.Equals(month)).Select(x=>x.Amount))

但后来我得到了这个运行时错误:“模板只能用于字段访问、属性访问、单维数组索引或单参数自定义索引器表达式。”

这是我的观点代码:

@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; }
}

【问题讨论】:

  • 我想我应该使用局部视图而不是第二个 foreach。

标签: c# asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

您应该考虑使用Partial Views

@Html.Partial("_months", Months)

那么您的局部视图可能如下所示:

@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>

【讨论】:

  • 很高兴能提供帮助。如果这是您想要的答案,请考虑accepting
【解决方案2】:

试试这个:

@for(int i=0; i<item.Months.Count; i++)
{
    <td>
        @Html.DisplayFor(modelItem => item.Months[i].Amount)
    </td>
}

【讨论】:

  • 它解决了我的问题,但我将实现部分视图。还是谢谢你。
猜你喜欢
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多