apero apero - 3 months ago 8
HTML Question

How to end a tag in Razor without razor complaining no start tag

I got this code:

@foreach (var team in Model.GetTeams)
{
var i = 0;
foreach (var employee in team.Medewerkers)
{
if (i == 0)
{
@:<li class="flip-card">
@:<div class="flip-card-back">
@:</div>
i=1;
}
else
{
@:<div class="flip-card-front">
@:</div>
@:</li>
i = 0;
}
}
if (i == 1)
{
</li>
}
}


Now it's possible that there are 3 employees in a team so the
li
tag would never close. So I thought I would add an if statement at the end to check if
i == 1
so I can close the
li
tag but when I use this code, Razor complains that I close a tag which is never started.

How can I achieve this goal?

Answer

Looks like you want to close <li class="flip-card"> after every two employees, or after the last employee when the number of employees is odd. For example you want this output when there are 2 employees

<li class="flip-card">
    <div class="flip-card-back">
    </div>
    <div class="flip-card-front">
    </div>
</li>

and you want this output when there are 3 employees

<li class="flip-card">
    <div class="flip-card-back">
    </div>
    <div class="flip-card-front">
    </div>
</li>
<li class="flip-card">
    <div class="flip-card-back">
    </div>
</li>    

Instead of changing the value of i to 0 and 1, I would suggest keep adding the value of i by 1 and use % operator to check whether the current value of i is odd or even. The closing </li> should only be added when i is odd or i equals team.Medewerkers.Count - 1. Change your code as below

@foreach (var team in Model.GetTeams)
{
    var i = 0;
    foreach (var employee in team.Medewerkers)
    {
        if (i == 0 || i % 2 == 0)
        {
            @:<li class="flip-card">
                @:<div class="flip-card-back">
                @:</div>
        } 
        else
        {
                @:<div class="flip-card-front">
                @:</div>
        }
        if (i % 2 == 1 || i == team.Medewerkers.Count - 1)
        {
            </li>
        }
        i++;  
    }
}