首页 > 解决方案 > 当模型是 IEnumerable 时,如何在 asp-for 标签助手中使用本地化

问题描述

在我看来,模型来自 type IEnumerable<ApplicationUser>asp-for在此模型中使用标签参数的最佳实践是什么?

我的意思是:当模型来自类型ApplicationUser并且我们创建一个简单的“编辑所有数据”模型时,我们可以简单地执行以下操作:

<label asp-for="Model.FirstName"></label>
<input asp-for="Model.FirstName"></input>
<label asp-for="Model.LastName"></label>
<input asp-for="Model.LastName"></input>

但是现在我的模型是一个IEnumerable<ApplicationUser>(并且我想利用资源本地化和DisplayAttributeof ApplicationUser)并且我想写一个表:

<table>
    <tr>
        <th><label asp-for="??? FirstName ???"></label></th>
        <th><label asp-for="??? LastName ???"></label></th>

        <th>&nbsp;</th>
    </tr>

    @foreach (var user in Model)
    {
        <tr>
            <td>@user.FirstName</td>
            <td>@user.LastName</td>
            <td><a asp-action="EditUser" asp-controller="Administrator" asp-route-id="@user.Id">edit profile</a></td>
        </tr>
    }
</table>

如何asp-for<th>...</th>标签中使用?我错过了什么?

标签: c#asp.net-coreasp.net-core-mvcasp.net-core-tag-helpers

解决方案


因此,为了在这里提供答案,我们只需使用IEnumerable<T>. 以上来自@jmcilhinney 和@Tseng 的评论帮助很大

<table>
    <tr>
        <th><label asp-for="First().FirstName"></label></th>
        <th><label asp-for="First().LastName"></label></th>

        <th>&nbsp;</th>
    </tr>
    ....
</table>

我将用 an 包围它if (Model != null && Model.Any())以确保它既不会抛出 aNullReferenceException也不会抛出IndexOutOfRangeException.


推荐阅读