有一种编写这段代码的最佳方法吗? (如果索引i处的元素不为null,则不进行验证)
我想在每行加载3个自举卡并将其放入3列
示例和代码:
1. CARD 1 CARD 2 CARD 3
2. CARD 4 CARD 5 CARD 6
@for (int i = 0; i < Model.Count()-1; i+=3)
{
<div class="row top30">
<div class="col-md-4">
@Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i))
</div>
@if (Model.ElementAtOrDefault(i + 1) != null)
{
<div class="col-md-4">
@Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i + 1))
</div>
}
@if (Model.ElementAtOrDefault(i + 2) != null)
{
<div class="col-md-4">
@Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i + 2))
</div>
}
</div>
}
答案 0 :(得分:1)
这个更短
@for (int i = 0; i < Model.Count()-1; i+=3)
{
<div class="row top30">
@for (int j = 0; j < 3; j++)
{
@if (j == 0 || (Model.ElementAtOrDefault(i + j) != null))
{
<div class="col-md-4">
@Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i + j))
</div>
}
}
</div>
}
答案 1 :(得分:0)
你可以循环遍历所有卡片,只有当它已经是第三张卡片时才插入一个新行:
<div class="row top30">
@for (int i = 0; i < Model.Count()-1; i++)
{
@if (Model.ElementAtOrDefault(i) != null)
{
<div class="col-md-4">
@Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i))
</div>
}
@if (i == 2)
{
</div>
<div class="row top30">
}
}
</div>
}