(MVC 3剃须刀) - 通过3列格更简单的方法来循环((MVC 3 Razor) - Easier

2019-09-17 00:05发布

目前,我用我的CSHTML下面的代码:

@{int i = 0;}
@foreach (var item in Model.Traders)
{
    if ((i++ % 3) == 0) {
        if (i != 1) {
            @:</div>
        }
        @:<div class="row">
    }

    @:<div class="four column"><div class="panel new"><h3 class="dotted"><strong>@item.Title</strong></h3><p>@item.Description</p><code>&lt;div class=&quot;panel pick&quot;&gt;</code></div></div>
}

@if (i != 0) {
    @:</div>
}

这种输出以下HTML:

<div class="row">
    <div class="four column"><div class="panel new"><h3 class="dotted"><strong>Title</strong></h3><p>Description</p><code>code</code></div></div>
    <div class="four column"><div class="panel new"><h3 class="dotted"><strong>Title</strong></h3><p>Description</p><code>code</code></div></div>
    <div class="four column"><div class="panel new"><h3 class="dotted"><strong>Title</strong></h3><p>Description</p><code>code</code></div></div>
</div>
<div class="row">
    <div class="four column"><div class="panel new"><h3 class="dotted"><strong>Bobby</strong></h3><p>Bobby bobby bobby</p><code>&lt;div class=&quot;panel pick&quot;&gt;</code></div></div>
    <!-- Add missing divs if there's less than 3 (there always needs to be 3 divs inside a div row). In this case it's 2 that are missing -->
    <div class="four column"></div> <!-- my code does not render these -->
    <div class="four column"></div> <!-- my code does not render these -->
</div>

我的问题是,是否有一个更简单的方法来实现什么我我的观点中做,并确保它添加缺少的div,如果有连续的小于3。

Answer 1:

集团贸易商批量的3项,试试这个:

@{

    var g = Model.Traders.GroupBy(r => Model.Traders.IndexOf(r) / 3).ToList();
}

@foreach (var parentItem in g)
{ 
    <div class="row">
        @foreach (var item in parentItem)
        { 
           <div class="four column"><div class="panel new"><h3 class="dotted"><strong>@item.Title</strong></h3><p>@item.Description</p><code>&lt;div class=&quot;panel pick&quot;&gt;</code></div></div>


        }


    @for (int i = parentItem.Count(); i < 3; i++)
    { 
        <div class="four column"></div>
    }
    </div>
}

问候。



文章来源: (MVC 3 Razor) - Easier way to loop through 3 column div