I use ASP.NET MVC and bootstrap. I have many objects (>2) in collection and for each need a <div class="col-xs-6"> but with only 2 cols in a row. How to achive this using loop?
There is 1 way but I am looking for something better:
@model List<Object>
@using (Html.BeginForm("ActionName", "ControllerName"))
{
<div class="row">
@for (int i = 0; i < Model.Count; i++)
{
if (i % 2 != 0) {
<div class="row">
<div class="col-xs-6">
@Html.TextBoxFor(o => o[i].Value)
</div>
</div>
} else {
<div class="col-xs-6">
@Html.TextBoxFor(o => o[i].Value)
</div>
}
}
</div>
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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>
Method 2
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;
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0