MVC Razor View - 每n个项目包含用foreach循环构造的行

时间:2011-07-14 14:05:53

标签: asp.net-mvc-3 razor

我有一个类似于此的Razor视图:

@foreach (var item in Model.Items)
{
    <div class="product">
        <a class="hide" href="#">
            <img src="#" alt="Hide" />
        </a><a href="#">
            <img src="#" width ="138" height="140" alt="product name" />
        </a>
        <h4 class="title">@Html.Raw(@item.Name)</h4>
        <span class="price">@item.Price.ToString("C")</span> 
    </div>
}

这很好用,并输出所需的html 然而, 我需要用一个包裹每个“行” <div class="ClearFix"></div> - 否则布局会在几行后变得混乱。

(在我的情况下,一行是5个产品div)

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:1)

@foreach (var row in Model.Items.Select((item, index) => new { index, item }))
{
    if (row.index % 5 == 0)
    {
        <div class="ClearFix"></div>
    }
    <div class="product">
        <a class="hide" href="#">
            <img src="#" alt="Hide" />
        </a>
        <a href="#">
            <img src="#" width ="138" height="140" alt="product name" />
        </a>
        <h4 class="title">@Html.Raw(@row.item.Name)</h4>
        <span class="price">@row.item.Price.ToString("C")</span> 
    </div>
}

答案 1 :(得分:0)

简单的int ii % 5 == 0 and i > 5不应该这样做吗?

答案 2 :(得分:0)

如果你真的需要将内容包装在clear fix div中......

@{
   var grouping = new List<Item>();
   var itemsPerRow = 5;
   for (var i = 0; i < Model.Items.Count; i++)
   {
     var item = Model.Items[i];
     grouping.Add(item);
     if (i>0 && i%itemsPerRow == itemsPerRow-1)
     {
       <div class="clear-fix">
           @foreach (var thing in grouping)
           {
              Html.RenderPartial("_ItemPartial", thing);
            }
       </div>
       grouping.Clear();
     }         
    }
}

然后在_ItemPartial.cshtml中:

@model Item
<div class="product">
    <a class="hide" href="#">
        <img src="#" alt="Hide" />
    </a><a href="#">
        <img src="#" width ="138" height="140" alt="product name" />
    </a>
    <h4 class="title">@Html.Raw(@Model.Name)</h4>
    <span class="price">@Model.Price.ToString("C")</span> 
</div>