How properly generate bootstrap grid via loop using Razor?
Close the row div
and start a new one inside the loop on every 2nd iteration
<div class="row">
@for (int i = 0; i < Model.Count; i++)
{
if (i > 0 && i % 2 == 0)
{
@:</div><div class="row"> // close and start new row
}
<div class="col-xs-6">
@Html.TextBoxFor(o => o[i].Value)
</div>
}
</div>
Using a combination of the split method found here (which I turned into a helper method)
https://www.jerriepelser.com/blog/approaches-when-rendering-list-using-bootstrap-grid-system/
and a for loop I managed to achieve the grid with indexed items
public static class SplitListHelper
{
public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size)
{
for (var i = 0; i < (float)array.Length / size; i++)
{
yield return array.Skip(i * size).Take(size);
}
}
}
@if (Model != null)
{
int rowCount = 0;
foreach (var row in Model.ToArray().Split(4))
{
<div class="row">
@for (int i = 0; i < row.Count(); i++)
{
<div class="col-xs-3">
@Html.DisplayFor(m => Model[rowCount + i].Name)
@Html.CheckBoxFor(m => Model[rowCount + i].Selected)
</div>
}
</div>
rowCount += 4;
}
}