Strongly typed helpers inside @model IEnumerable <>

Why can't I 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... *@ } 

Error message

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

Any ideas? Thanks.

+4
source share
2 answers

Try this way. You need to access the name from this element.

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

I think I know what you are trying to do.

First of all, it seems that the model parameter that you use in your lambda expression is a reserved word in the browser - this is what causes an error of your type.

secondly, in order to solve your enumerable problem, in order to get both the label and the value, you will have to use the index of the value in IEnumerable

eg:

 @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 only has a for loop, as there is currently no need to list the collection

 @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... *@ } 
+4
source

Source: https://habr.com/ru/post/1481673/


All Articles