Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use LabelFor on a strongly typed view for a list

When I used asp.net mvc 3 scaffolding to make a list. I got a view containing a table. With the headers of that table hard coded in the view. I want to use LabelFor, so I get the l10n I need.

What I tried to do (but failed) was:

@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>

It errors with "IEnumerable does not contain a definition for Name".. etc...

How do I make this work?

like image 346
dvdvorle Avatar asked Jul 15 '11 06:07

dvdvorle


People also ask

What does it mean for a view to be strongly typed?

A Strongly Typed view means it has a ViewModel associated to it that the controller is passing to it and all the elements in that View can use those ViewModel propertiesYou can have strongly typed partials as well.

What are the advantages of using strongly typed views?

The ASP.NET Core provides the ability to pass strongly typed models or objects to a view. This approach helps us with the intellisense and better compile-time checking of our code. The scaffolding mechanism in Visual Studio can be used to create the View.


1 Answers

Try with some like

@(Html.LabelFor<User, string>(model => model.FirstOrDefault().Name))
like image 164
Jonathan Avatar answered Sep 22 '22 00:09

Jonathan