Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DisplayNameFor() From List<Object> in Model

I believe this is pretty simple, I just can't seem to find the right way to show the display name for an item within a list within my model.

My simplified model:

public class PersonViewModel {     public long ID { get; set; }          private List<PersonNameViewModel> names = new List<PersonNameViewModel>();      [Display(Name = "Names")]     public List<PersonNameViewModel> Names { get { return names; } set { names = value; } }       } 

and Names:

public class PersonNameViewModel {     public long ID { get; set; }      [Display(Name = "Set Primary")]     public bool IsPrimary { get; set; }      [Display(Name = "Full Name")]     public string FullName { get; set; } } 

Now I'd like to make a table to show all the names for a person, and get the DisplayNameFor FullName. Obviously,

@Html.DisplayNameFor(model => model.Names.FullName); 

wouldn't work, and

@Html.DisplayNameFor(model => model.Names[0].FullName);   

will break if there are no names. Is there a 'best way' to obtain the display name here?

like image 264
Jonesopolis Avatar asked Dec 27 '13 21:12

Jonesopolis


1 Answers

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) 
like image 100
Tim S. Avatar answered Oct 11 '22 01:10

Tim S.