DisplayNameFor() From List<Object> in Model
This actually works, even without items in the list:
@Html.DisplayNameFor(model => model.Names[0].FullName)
It works because MVC parses the expression instead of actually executing it. This lets it find that right property and attribute without needing there to be an element in the list.
It's worth noting that the parameter (model
above) doesn't even need to be used. This works, too:
@Html.DisplayNameFor(dummy => Model.Names[0].FullName)
As does this:
@{ Namespace.Of.PersonNameViewModel dummyModel = null; }
@Html.DisplayNameFor(dummyParam => dummyModel.FullName)
There is another way for do it, and i guess that is more clear:
public class Model
{
[Display(Name = "Some Name for A")]
public int PropA { get; set; }
[Display(Name = "Some Name for B")]
public string PropB { get; set; }
}
public class ModelCollection
{
public List<Model> Models { get; set; }
public Model Default
{
get { return new Model(); }
}
}
And then, in the view:
@model ModelCollection
<div class="list">
@foreach (var m in Model.Models)
{
<div class="item">
@Html.DisplayNameFor(model => model.Default.PropA): @m.PropA
<br />
@Html.DisplayNameFor(model => model.Default.PropB): @m.PropB
</div>
}
</div>
As an alternate solution you could try:
@Html.DisplayNameFor(x => x.GetEnumerator().Current.ItemName)
It will work even if the list is empty!