Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-tag-helpers

How to use localization in asp-for tag helper, when the model is an IEnumerable<T>


In my view, the model is from type IEnumerable<ApplicationUser>. What is best practice to use the asp-for tag-parameter with this model?

What I mean is: when the model is from type ApplicationUser and we create a simple "Edit-All-Data"-model we simply can do something like this:

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

But now my model is an IEnumerable<ApplicationUser> (and I want to take advantage of localization with resources and DisplayAttribute of ApplicationUser) and I want to write a table:

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

How can I use the asp-for in the <th>...</th> tags? Did I miss something?


Solution

  • So to provide an answer here, we just can use the extension-methods of IEnumerable<T>. The comments above from @jmcilhinney and @Tseng helped a lot

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

    I'm going to surround this with an if (Model != null && Model.Any()) to ensure, this throws neither a NullReferenceException nor an IndexOutOfRangeException.