Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Html.DisplayNameFor for details model

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?

like image 981
Alex Avatar asked Feb 21 '12 23:02

Alex


People also ask

What is DisplayNameFor in Mvc?

The DisplayNameFor shows the name of the property or the string defined in the display attribute for the property.

How to Add model in cshtml page?

cshtml file we need to right click on GetEmployeeInfo() Action Method & Click on Add View. From the Add View Window, give the View Name as GetEmployeeInfo, Template as Create, and Model class as EmployeeInfo. cs and click on Add, with this GetEmployeeInfo. cshtml file will be added in Views Folder.

How to Add model in. net core?

In Solution Explorer, right-click the Controllers folder and select Add > New Scaffolded Item. In the Add Scaffold dialog, select MVC Controller with views, using Entity Framework > Add. Complete the Add MVC Controller with views, using Entity Framework dialog: In the Model class drop down, select Movie (MvcMovie.

How to Add model Class in Mvc view?

Adding a Model Class In the MVC application in Visual Studio, and right-click on the Model folder, select Add -> and click on Class... It will open the Add New Item dialog box. In the Add New Item dialog box, enter the class name Student and click Add. This will add a new Student class in model folder.


1 Answers

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.

like image 52
Red Taz Avatar answered Sep 22 '22 07:09

Red Taz