SamJolly
SamJolly

Reputation: 6477

How to access DisplayName annotation within loop rather than from Model in Razor View?

This is probably a basic question, but I am currently missing the light on this one.

I usually use :

@Html.LabelFor(model=>model.myProperty)
@Html.DisplayFor(model=>model.myProperty)

Which displays the DisplayName annotation, from the View Model, for the property. Also DisplayFor displays the value.

However what if I want to iterate through a Model List and then do the same?

@foreach (var item in Model.myPropertyList)
{
  @Html.LabelFor(item=>item.myProperty) //No longer works
  @Html.DisplayFor(item=>item.myProperty) // No Longer works.
}

What should the code be in the foreach loop to pickup the Property DisplayName and value.

I realise that the following will work for displaying the value:

@item.myProperty

EDIT:

Answer seems to be:

@Html.DisplayNameFor(modelItem=>item.myProperty)
@Html.DisplayFor(modelItem=>item.myProperty)

Found by helpers here and me.... team effort.... Thanks

Upvotes: 1

Views: 1133

Answers (3)

SamJolly
SamJolly

Reputation: 6477

@Html.DisplayNameFor(modelItem=>item.myProperty)
@Html.DisplayFor(modelItem=>item.myProperty)

Upvotes: 1

shady youssery
shady youssery

Reputation: 440

you can use this :

@Html.DisplayFor(model=>item.myProperty)

Upvotes: 2

Chandan Kumar
Chandan Kumar

Reputation: 4638

Check with the below one

<div>
        <table border="1" class="col-md-12 text-center table-font table-hover table-striped table" id="tblTemp">
            <thead>
                <tr>
                    <th class="text-center" style="color:#000;">
                        My Property For Label
                    </th>
                    <th class="text-center" style="color:#000;">
                        My Property For Textbox
                    </th>                        
                </tr>
            </thead>
            <tbody>

     @foreach (var item in Model.myPropertyList)
     {
       <tr>
           <td class="text-left">
               @Html.LabelFor(modelItem=>item.myProperty) //Should work
           </td>
           <td class="text-left">
               @Html.DisplayFor(modelItem=>item.myProperty) // Should work
           </td>
        </tr>
      }
     </tbody>
   </table>
</div>

Upvotes: 1

Related Questions