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?
You can add a @using statement to your View to specify the Carrier type, then you will need to loop through your Model's Carriers property.
Your View will look something like..
I had a similar requirement, but I needed to get display names for properties from a different non-enumerable class so the solution from @plurby wouldn't have worked. I ended up solving this by creating a fluent call that can be used to get a new HtmlHelper for any arbitrary type. The code for the extension and adapter is:
You can then use this in the view like this:
One of the advantages is that this approach will work for any HtmlHelper extension, not just
DisplayNameFor
(but keep in mind that the adapted HtmlHelper does not have any view data since that's all typed based on the model being used in the view and thus won't work in the adapted HtmlHelper).I found there was no need for helper methods, extra code or looping through the collection. I just used the following:
This still works even if
FirstOrDefault()
would returnnull
because it's only looking for meta data, theName
property itself is not accessed.Many thanks to @Kurian who inspired this answer.
Here is an approach, which is based on the original
DisplayNameFor
extension method and works consistent.An extension method for
HtmlHelper
:And that's how it could be used in a view:
I've got a similar problem, because i don't want to type my column names by hand so i wrote a helper:
Then in the view you'll call it
Please note that you can use Display attribute which accepts Name and many other customization like Resource file etc.