Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Html.DisplayNameFor on a complex model

I have a model with a complex type i.e. User/Addresses/List of Addresses

public class User{
public List<Address> Addresses{get;set;}
}

On my View I am displaying this

<fieldset><legend>@Html.DisplayNameFor(model=>model.Addresses)</legend>
<table>       
<tr>
    <th>
        @Html.DisplayNameFor(m => Model.Addresses.Street)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Addresses.City)
    </th>
<th>
        @Html.DisplayNameFor(model => model.Addresses.State)
    </th>

    </tr>
@foreach (var item in Model.Addresses) {    
<tr>
    <td>
        @Html.DisplayFor(m => item.Street)
    </td>
    <td>
        @Html.DisplayFor(m => item.City)
    </td>
    <td>
        @Html.DisplayFor(m => item.State)
    </td>
</tr>
} 
    </table></fieldset>

The DisplayNameFor Street/City/State do not work.

What is the proper way to get the DisplayNameFor on a sub object?

TIA J

like image 443
John S Avatar asked Aug 28 '12 22:08

John S


1 Answers

I changed

@Html.DisplayNameFor(m => Model.Addresses.Street)

to

@Html.DisplayNameFor(m => Model.Addresses.FirstOrDefault().Street)

Do not use @Html.DisplayNameFor(m => Model.Addresses[0].Street) because if you need to edit the first row, you won't be able this way.

Everything works as expected now.

like image 119
John S Avatar answered Sep 20 '22 18:09

John S