richardjgreen
richardjgreen

Reputation: 69

Unbalanced DIV Closing DIV with MVC Razor For Each Loop

I'm using Bootstrap 3 on my site and I am using an MVC Razor For Each Loop to retrieve all of the child items on a blog homepage as follows:

@{int i = 0;}
@foreach (var subPage in Model.Content.AncestorOrSelf(2).Children.OrderBy("createDate descending"))
{
    if (i % 2 == 0)
    {
        @:<div class="row row-eq-height">
    }

    <div class="col-sm-12 col-md-6">
    </div><!-- col-sm-12 col-md-6 -->

    if (i % 2 != 0)
    {
        @:</div><!-- row row-eq-height -->
    }
    i++;
}

This works fine when I have an even number of child pages however when I have an odd number of child pages, it's not hitting the if % 2 != 0 block which means the last row doesn't get closed which then breaks the flow of the remainder of the page.

I tried to fix this by adding the following if statement after the For Each loop hoping that if the final value of i was not 2, it would add a closing DIV tag as needed but instead that causes an inbalanced DIV tag error.

@if (i !% 2 == 0)
{
    </div><!-- row row-eq-height -->
}

Anyone got any thoughts or ideas? If I have an even number, it works just fine and the page flow is as expected.

Upvotes: 2

Views: 1547

Answers (1)

user3559349
user3559349

Reputation:

Your foreach loop needs to be inside a the containing element (row) and then withing the loop, close and start a new row for every second child element (column)

@{int i = 0;}
<div class="row row-eq-height">
    @foreach (var subPage in Model.Content.AncestorOrSelf(2).Children.OrderBy("createDate descending"))
    {
        if (i > 0 && i % 2 == 0)
        {
            @:</div><div class="row row-eq-height">
        }
        <div class="col-sm-12 col-md-6">xxxxx</div>
        i++;
    } 
</div>

The output, assuming you have 5 items in the collection, will be

<div class="row row-eq-height">
    <div class="col-sm-12 col-md-6">xxxxx</div>
    <div class="col-sm-12 col-md-6">xxxxx</div>
</div>
<div class="row row-eq-height">
    <div class="col-sm-12 col-md-6">xxxxx</div>
    <div class="col-sm-12 col-md-6">xxxxx</div>
</div>
<div class="row row-eq-height">
    <div class="col-sm-12 col-md-6">xxxxx</div>
</div>

Upvotes: 4

Related Questions