MVC Html.DisplayNameFor on a complex model

10,307

Solution 1

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.

Solution 2

You can also use the Linq to avoid the indexing error. I used this is my code -

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

And the following error went away.

Cannot apply indexing with [] to an expression of type 'System.Data.Objects.DataClasses.EntityCollection<Address>

However it's better to use the Name directly using the following statement

@Html.DisplayName("Street")

Solution 3

This could be better:

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

will also work in case the list is empty

Share:
10,307

Related videos on Youtube

John S
Author by

John S

Been around since the days of Business Basic and the 6502. Currently working mostly in the Microsoft stack, C#, SQL, etc.. Also work with SCSS, CSS, JQuery, Javascript. Currently a Software Engineer that likes to keep up on some aspects of the IT side of things so that I can do a better job writing my software. Always striving to understand the whole problem domain not just the algorithm.

Updated on July 31, 2022

Comments

  • John S
    John S over 1 year

    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

  • Zapnologica
    Zapnologica over 9 years
    So whats your solution?