Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mix of html and code in foreach in razor

I want to create bootstrap grid with row-fluid class. It is need to separate all nested div's with span4 class into blocks. So I want to have html like this:

    <div class="row-fluid">
        <div class="span4"></div>
        <div class="span4"></div>
        <div class="span4"></div>
    </div>
    <div class="row-fluid">
        <div class="span4"></div>
        <div class="span4"></div>
        <div class="span4"></div>
    </div>

And I have code in razor

@{
int counter = 3;
}
@foreach (var config in Model)
{
    @if (counter == 3)
    {
       <div class="row-fluid">
       @counter = 0;
    }
    @Html.Partial("_ConfigBar", config)

    @if (counter == 2)
    {
        </div>
    }
    @{counter++;}
}

Partial view just put div with span4 class, and there are nothing interesting.

But it didn't work. Can anyone point me what is wrong?

like image 827
Max Avatar asked Aug 11 '13 14:08

Max


1 Answers

Something like this should create what you need:

@{
    int counter = 0;
    foreach (var config in Model)
    {
        if (counter == 0)
        {
           @Html.Raw("<div class=\"row-fluid\">")
        }
        else if (counter > 0 && counter % 3 == 0 )
        {
           @Html.Raw("</div><div class=\"row-fluid\">")
        }

        @Html.Partial("_ConfigBar", config)

        counter++;
    }

    @Html.Raw("</div>")
}

This will:

  • create an opening div on the first loop
  • close the current open div and open a new div on each 4th loop
  • add a closing div once the looping is complete.
like image 174
Digbyswift Avatar answered Nov 01 '22 21:11

Digbyswift