How to use LabelFor a strongly typed view for a list

When I used asp.net mvc 3 scaffolding to create a list. I have a view containing a table. With the headings of this table hardcoded in the view. I want to use LabelFor, so I get the l10n that I need.

What I tried to do (but failed):

@model IEnumerable<User> <table> <tr> <th> @(Html.LabelFor<User, string>(model => model.Name)) <!--This line errors--> </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> </table> 

Errors with "IEnumerable do not contain a definition for the name", etc.

How do I do this job?

+8
c # asp.net-mvc-3 razor
source share
4 answers

Try something like

 @(Html.LabelFor<User, string>(model => model.FirstOrDefault().Name)) 
+19
source share

Your view model is not adapted to what you are trying to achieve. Here's what the best review model would look like:

 public class MyViewModel { // This property represents the header value // you could use data annotations to localize it [Display(.. some localization here ..)] public string NameHeader { get; set; } // This property represents the data source that // will be used to build the table public IEnumerable<User> Users { get; set; } } 

and then:

 @model MyViewModel <table> <tr> <th> @Html.LabelFor(x => x.NameHeader) </th> </tr> @foreach (var item in Model.Users) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> </tr> </table> 

and with the display template you donโ€™t even need to write a foreach :

 @model MyViewModel <table> <tr> <th> @Html.LabelFor(x => x.NameHeader) </th> </tr> @Html.DisplayFor(x => x.Users) </table> 

and inside a custom display template ( ~/Views/Shared/DisplayTemplates/User.cshtml ):

 @model User <tr> <td>@Html.DisplayFor(x => x.Name)</td> </tr> 
+4
source share

You wrap the label before (or outside) the foreach iteration, so you are trying to access the Name property in an IEnumerable collection that does not exist.

0
source share

Use DisplayNameFor @ Html.DisplayNameFor (model => model.Name) instead

0
source share

All Articles