ffxdean ffxdean - 23 days ago 5
ASP.NET (C#) Question

Error: "foreach statement cannot operate on variables"

I'm having difficulties figuring out how to solve this error message:


Error CS1579 foreach statement cannot operate on variables of type 'A1.Models.Reviews' because 'A1.Models.Reviews' does not contain a public definition for 'GetEnumerator' A1..NETCoreApp,Version=v1.0


@foreach (var item in Model)
{
<content>
<header>
<hr id="ReviewsSide" />
<h6><b>&#64 @Html.DisplayFor(ModelItem => item.Heading)</b></h6>
</header>
<p>
Rating;

@{
int numStars = 0;

if (item.Rating == 5)
{
numStars = 5;
}
else if (item.Rating == 4)
{
numStars = 4;
}
else if (item.Rating == 3)
{
numStars = 3;
}
else if (item.Rating == 2)
{
numStars = 2;
}
else
{
numStars = 1;
}



for (int i = 0; i < numStars; i++)
{
<span style="color: #f8bd08; ">&#x2605;</span>
}
for (int i = 0; i < 5 - numStars; i++)
{
<span>&#x2606;</span>
}


}
</p>
}


Any ideas?

I've added the following code to the top of my cshtml page but still the same error message:

IEnumerable<A1.Models.Reviews>
@model Reviews


Thankyou

Answer

You need to replace

IEnumerable<A1.Models.Reviews>
@model Reviews

With

@model IEnumerable<A1.Models.Reviews>

In order to pass a sequence of reviews to your Razor View And be able to iterate over it.

The error shown means that the type being passed is not a sequence and though you can't iterate over it.

With that being said, you need also to make sure that you're passing a sequence from your controller to your View, so that these 3 parts work without any problem.

Comments