在C#中,我尝试使用嵌套foreach
来显示文章列表。我给出的平面HTML要求每3篇文章<div class="row">
。
我只是显示文章的原始代码如下:
@foreach (var article in Model)
{
<div class="spanthird col">
<div class="well">
<article>
<h3>@article.UrlStringDisplay</h3>
<div class="date">@article.Date.ToString("dd MMMM yyyy")</div>
<a href="@Url.RouteUrl("PressReleases", new {id = article.UrlString, Action = "article", Controller = "PressReleases"})" class="btn btn-primary">Read more</a>
</article>
</div>
</div>
}
我想为每3篇文章包含div class =“row”。我已经达到了这一点,但它在第一个foreach
中对'数据'进行了'酝酿'。
int i = 0;
foreach (var row in )
{
if (i % 3 == 0) {
@:<div class="row">
}
foreach (var article in Model)
{
<div class="spanthird col">
<div class="well">
<article>
<h3>@article.UrlStringDisplay</h3>
<div class="date">@article.Date.ToString("dd MMMM yyyy")</div>
<a href="@Url.RouteUrl("PressReleases", new {id = article.UrlString, Action = "article", Controller = "PressReleases"})" class="btn btn-primary">Read more</a>
</article>
</div>
</div>
}
if (i % 3 == 2 || i == data.Count() - 1)
{
@:</div>
}
i++;
}
我快到了。我只需要朝着正确的方向轻推。
答案 0 :(得分:3)
这是我能想到的最干净的:
@for (int i = 0; i < Model.Count; i+=3)
{
<div class="row">
@foreach (var article in Model.Skip(i).Take(3))
{
<div class="spanthird col">
<div class="well">
<article>
<h3>@article.UrlStringDisplay</h3>
<div class="date">@article.Date.ToString("dd MMMM yyyy")</div>
<a href="@Url.RouteUrl("PressReleases", new {id = article.UrlString, Action = "article", Controller = "PressReleases"})" class="btn btn-primary">Read more</a>
</article>
</div>
</div>
}
</div>
}
答案 1 :(得分:0)
int row = 1;
@foreach (var article in Model)
{
@if(row == 1)
@:<div class="row">
<div class="spanthird col">
<div class="well">
<article>
<h3>@article.UrlStringDisplay</h3>
<div class="date">@article.Date.ToString("dd MMMM yyyy")</div>
<a href="@Url.RouteUrl("PressReleases", new {id = article.UrlString, Action = "article", Controller = "PressReleases"})" class="btn btn-primary">Read more</a>
</article>
</div>
</div>
@if(row == 3)
@:</div>
<% row++; %>
@if(row == 4)
<% row = 1; %>
}
@if(i != 1)
@:</div>