如何使用Razor通过循环正确生成引导网格?

我使用ASP.NET MVC和bootstrap。 我在集合中有很多对象(> 2),每个需要一个

但是连续只有2个

。 如何使用循环来实现这个目标? 有一种方法,但我正在寻找更好的东西:

 @model List @using (Html.BeginForm("ActionName", "ControllerName")) { 
@for (int i = 0; i < Model.Count; i++) { if (i % 2 != 0) {
@Html.TextBoxFor(o => o[i].Value)
} else {
@Html.TextBoxFor(o => o[i].Value)
} }
}

关闭行div并在每次第二次迭代时在循环内开始一个新行

 
@for (int i = 0; i < Model.Count; i++) { if (i > 0 && i % 2 == 0) { @:
// close and start new row }
@Html.TextBoxFor(o => o[i].Value)
}

使用此处找到的split方法的组合(我将其转换为辅助方法)

https://www.jerriepelser.com/blog/approaches-when-rendering-list-using-bootstrap-grid-system/

和一个for循环我设法用索引项目实现网格

 public static class SplitListHelper { public static IEnumerable> Split(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)) { 
@for (int i = 0; i < row.Count(); i++) {
@Html.DisplayFor(m => Model[rowCount + i].Name) @Html.CheckBoxFor(m => Model[rowCount + i].Selected)
}
rowCount += 4; } }