Uthman Rahimi Uthman Rahimi - 7 months ago 28
HTML Question

Cant closing Tag in foreach with Razor - ASP.NET MVC

I have a

div
and each
div
has two
divs
in it like this:

<div class="col">
<div class="item-c color1">..</div>
<div class="item-c color2">..</div>
</div>


I read data from database and I want to repeat this div with a
foreach
statement.

I use below code but I get a
Runtime Error


<div class="col">
@foreach (var item in Model)
{

<div class="item-c @("color" + index.ToString()) ">..</div>
if (index % 2 == 0)
{
<text></div><div class="col"></text>
}
index++;
if (index > 8) { index = 1; }
}


my result should like this :
enter image description here
I am getting this Error :


Encountered end tag "div" with no matching start tag

Answer

Your code needs to be

@{ int index = 1; }

<div class="col">
    @foreach(var item in Model.Items)
    {
        <div class="item-c color@(index)">..</div>
        if (index % 2 == 0) // close the div and start a new one
        {
            @:</div><div class="col">
        }
        index++;
        if (index > 8) { index = 1; }
    }
</div>