Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 590
nomad Avatar asked Dec 15 '22 10:12

nomad


2 Answers

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)

}
like image 131
PSL Avatar answered Dec 24 '22 02:12

PSL


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.

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

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

@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... *@
}
like image 40
m.t.bennett Avatar answered Dec 24 '22 02:12

m.t.bennett