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?
The DisplayNameFor shows the name of the property or the string defined in the display attribute for the property.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With