(MVC 3剃须刀) - 通过3列格更简单的方法循环 [英] (MVC 3 Razor) - Easier way to loop through 3 column div

查看:94
本文介绍了(MVC 3剃须刀) - 通过3列格更简单的方法循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我使用下面的code在我CSHTML:

At the moment I'm using the following code in my 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:

This outputs the following 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连胜。

My question is whether there's an easier way to achieve what I'm doing within my view and to ensure that it adds the missing divs if there's less than 3 in a row.

推荐答案

集团在一批3项交易,试试这个:

Group traders in batch of 3 items, Try this:

@{

    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剃须刀) - 通过3列格更简单的方法循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆