c# - 如何将 html 助手用于通用集合?

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

我有一个强类型 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/

相关文章:

c# - 登录失败远程调试作为 Azure 应用服务托管的 ASP.NET WebAPI 服务

c# - 部分 View '/Views/Shared/... 未找到或没有 View 引擎支持搜索的位置

c# - 无法处理带有引用代码 [xxx] 的订单,该标志无效 PayU

c# - Unity编辑器捕获 "hold mouse down and move"事件

c# itextsharp PDF 创建在每页上带有水印

c# - 忽略生成查询表达式 EF Core 的 ThenIninclude 语句

c# - 模式和实践。服务层?

asp.net-mvc - 我怎么知道在 MVC 中重定向之前用户去过哪里?

c# - 订阅 MVC Controller 中的事件

c# - 带有 Newtonsoft 的 ASP.NET MVC 将对象从 Controller 传递到 View