简体   繁体   English

@model IEnumerable <>中的强类型助手

[英]strongly typed helpers inside @model IEnumerable<>

Why am I not able to use strongly typed helpers in the code below? 为什么我无法在下面的代码中使用强类型助手?

@using ISApplication.Models
@model IEnumerable<PersonInformation>

@foreach (PersonInformation item in Model)
{
    @Html.LabelFor(model => model.Name) // Error here.
    @item.Name // But this line is ok

    @* and so on... *@
}

The error message is 错误消息是

The type of arguments for method '...LabelFor<>... ' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Any ideas? 有任何想法吗? Thanks. 谢谢。

Try this way. 试试这种方式。 You need to access the Name from the item. 您需要从项目中访问名称。

@foreach (PersonInformation item in Model)
{
    @Html.LabelFor(x => item.Name); 
    @Html.DisplayFor(x =>item.Name)

}

I think I know what your trying to do. 我想我知道你想做什么。

First of all it would seem that the model parameter you are using in your lambda expression is a razor reserved word - this is what is causing your type error. 首先,您在lambda表达式中使用的模型参数似乎是一个剃刀保留字 - 这就是导致类型错误的原因。

secondly, to solve your enumerable problem, to get both label and value coming out you will have to use the index of the value in the IEnumerable 其次,为了解决你的可枚举问题,要获得标签和值,你将不得不使用IEnumerable中的值的索引

for example: 例如:

@using ISApplication.Models
@model IEnumerable<PersonInformation>
@
{
  List<PersonalInformation> people = Model.ToList();
  int i = 0;
}
@foreach (PersonInformation item in people)
{
    @Html.LabelFor(m => people[i].Name) // Error here.
    @Html.DisplayFor(m => people[i].Name) // But this line is ok

    @* and so on... *@
    i++;
}

EDIT: 编辑:

This method is with just a for loop, as currently there is no need to enumerate the collection 这个方法只有一个for循环,因为目前没有必要枚举该集合

@using ISApplication.Models
@model IEnumerable<PersonInformation>
@
{
  List<PersonalInformation> people = Model.ToList();
}
@for(int i = 0; i < people.Count; i++)
{
    @Html.LabelFor(m => people[i].Name) // Error here.
    @Html.DisplayFor(m => people[i].Name) // But this line is ok

    @* and so on... *@
}

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

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