我的foreach循环存在问题:
@for(int i = 0; i < Model.Count(); i += 3)
{
<div class="row">
@foreach (var item in Model)
{
<div class="col-md-4 portfolio-item">
<a href="@Html.DisplayFor(modelItem => item.UrlSlug)">
<img class="img-responsive" src="http://placehold.it/700x400" alt="">
</a>
<h3>
<a href="@Html.DisplayFor(modelItem => item.UrlSlug)">@Html.DisplayFor(modelItem => item.Title)</a>
</h3>
<p>@Html.DisplayFor(modelItem => item.ShortDescription)</p>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</div>
}
</div>
}
此方法显示一个很长的列表,但是我只想在填充了三个项目组合项目之后在<div class="col-md-4 portfolio-item">
内显示三个(3x)<div class="row">
然后我想创建另一个<div class="row">
并填充下一个三个<div class="col-md-4 portfolio-item">
。
我怎样才能做到这一点?
答案 0 :(得分:8)
您可以使用for (int i = 0; i < Model.Count; i += 3)
之类的外部for循环而不是<div class="row">
,并且您的实际foreach使用Model.Skip(i).Take(3)
。
@for(int i = 0; i < Model.Count(); i += 3)
{
<div class="row">
@foreach (var item in Model.Skip(i).Take(3))
{
<div class="col-md-4 portfolio-item">
<a href="@Html.DisplayFor(modelItem => item.UrlSlug)">
<img class="img-responsive" src="http://placehold.it/700x400" alt="">
</a>
<h3>
<a href="@Html.DisplayFor(modelItem => item.UrlSlug)">@Html.DisplayFor(modelItem => item.Title)</a>
</h3>
<p>@Html.DisplayFor(modelItem => item.ShortDescription)</p>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</div>
}
</div>
}