对于asp.net mvc视图中的索引循环

时间:2016-03-28 03:33:01

标签: asp.net asp.net-mvc for-loop razor

有一种编写这段代码的最佳方法吗? (如果索引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>
}

2 个答案:

答案 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>

}