简体   繁体   English

如何在列表的强类型视图上使用 LabelFor

[英]How to use LabelFor on a strongly typed view for a list

When I used asp.net mvc 3 scaffolding to make a list.当我使用 asp.net mvc 3 脚手架制作列表时。 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.我想使用LabelFor,所以我得到了我需要的l10n。

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...它出现“IEnumerable 不包含名称的定义”的错误......等等......

How do I make this work?我该如何进行这项工作?

Try with some like尝试一些喜欢

@(Html.LabelFor<User, string>(model => model.FirstOrDefault().Name))

Your view model is not adapted to what you are trying to achieve.您的观点 model 不适合您想要实现的目标。 Here's how a better view model would look like:以下是更好的视图 model 的样子:

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 a display template you don't even need to write a foreach loop:并且使用显示模板,您甚至不需要编写foreach循环:

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

and inside the custom display template ( ~/Views/Shared/DisplayTemplates/User.cshtml ):在自定义显示模板( ~/Views/Shared/DisplayTemplates/User.cshtml )中:

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

You render the Label before (or outside) of the foreach iteration, thus you try to access Name property in an IEnumerable collection which doesn't exist.您在 foreach 迭代之前(或之外)渲染 Label,因此您尝试访问不存在的 IEnumerable 集合中的 Name 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM