In my model I have an Entity
public class Carrier
{
public Guid CarrierId { get; set; }
public string Name { get; set; }
}
I also have a ViewModel
public class CarrierIndexViewModel
{
public IEnumerable<Carrier> Carriers { get; set; }
public PagingInfo PagingInfo { get; set; }
}
I have a strongly-typed (CarrierIndexViewModel) Index View, which is suppose to display a table of Carrier using PagingInfo.
I'm trying to use Html helper to display Carrier.Name in my table's header
When I used IEnumerable as a model for this view I had
@Html.DisplayFor(model => model.Name)
How can I get same result using my new CarrierIndexViewModel to display title for Carrier.Name?
I found there was no need for helper methods, extra code or looping through the collection. I just used the following:
@Html.DisplayNameFor(model => model.Carriers.FirstOrDefault().Name)
This still works even if FirstOrDefault()
would return null
because it's only looking for meta data, the Name
property itself is not accessed.
Many thanks to @Kurian who inspired this answer.