2011-07-14 104 views
0

我有了在这样的一个Razor视图:MVC Razor视图 - 用foreach循环构造包装行每n项

@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)

是否有这样做的方法吗?

回答

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> 
} 
0

应该不是一个简单的int ii % 5 == 0 and i > 5做的伎俩?

+0

你可以充实这个答案了位..?不知道我得到它... – Alex

0

如果你真的需要包装中明确固定股利内容...

@{ 
    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>