Apply different DIV in For each loop

Viewed 44

I am working on MVC 5. Using WEB API, fetch the data now it is time to apply the HTML PAGE design and CSS.

@foreach (var item in Model)
{
  if (Model.First() == item)
  {
        ///APPLY FIRST RECORD CSS:- Works FINE
  }
  else {
        <div class="row">
           <div class="col-sm-4">
           </div>
        </div>  
  }
}

In the else portion, every time it generates the new ROW for a SINGLE record. But I am interested to display record 2 3 4 in SECOND ROW. 5 6 7 Record in the THIRD ROW and so on.

1 Answers

If it is the first item, open a div and then put the items in it. Close the div when the number of columns is 3 or close the div if the item is at the end of the list.

The following algorithm does this for you

@{
    int i = 0;
    int columnCounter = 1;
    bool newRow = false;
}
@foreach (var item in Model)
{
    //add and open div row
    if (i == 0 || newRow)
    {
        newRow = false;
        @:<div class="row" style="border:2px solid red;">
    }
    <div class="col-md-4" style="padding:0;">
        <div style="height:40px;background:#f6f6f6;width:100%;text-align:center;">
             <span>Column @i</span>
        </div>
    </div>

    //close div row if column count == 3 or reach of end list
    if (columnCounter == 3 || i == Model.Count - 1)
    {
        newRow = true;
        columnCounter = 1;
        @:</div>
    }
    else
    {
        columnCounter = columnCounter + 1;
    }
}

result:

enter image description here

Related