Daniel Santos Daniel Santos - 3 months ago 28
ASP.NET (C#) Question

ASP.NET MVC. How use DisplayNameFor in order to create a table heading and body?

How get a property display name using

DisplayNameFor()
to build a table header. for instance:

@model IEnumerable<Item>
<table class="table">
<thead>
<tr>
<td>@Html.DisplayNameFor(? => ?.prop1)</td>
<td>@Html.DisplayNameFor(? => ?.prop2)</td>
<td>@Html.DisplayNameFor(? => ?.prop3)</td>
</tr>
</thead>
<tbody>
@foreach (Item item in Model) {
<tr>
<td>@Html.DisplayFor(i => item.prop1)</td>
<td>@Html.DisplayFor(i => item.prop2)</td>
<td>@Html.DisplayFor(i => item.prop3)</td>
</tr>
}
</tbody>
</table>


what should I write in the question marks?

Answer

You could do like this:

   @model IEnumerable<Item>
   <table class="table">
        <thead>
            <tr>
                <td>@Html.DisplayNameFor(i => i.First().prop1)</td>
                <td>@Html.DisplayNameFor(i => i.First().prop2)</td>
                <td>@Html.DisplayNameFor(i => i.First().prop3)</td>
            </tr>
        </thead>
        <tbody>
            @foreach (Item item in Model) {
                <tr>
                    <td>@Html.DisplayFor(i => item.prop1)</td>
                    <td>@Html.DisplayFor(i => item.prop2)</td>
                    <td>@Html.DisplayFor(i => item.prop3)</td>
                </tr>
            }    
        </tbody>
    </table>

It may look like you are actually getting the first item of the IEnumerable, but you are not.

Since the parameter you are passing to DisplayFor() is just an Expression Tree, it won't execute IEnumerable's First() method at all, internally DisplayFor() will only check for the passed type (the parameter's type) to use reflection and build a display for it.

Comments