每隔四行写出<div>和</div>

时间:2011-10-27 13:24:49

标签: c# asp.net-mvc asp.net-mvc-2

我试图在第四排写出div但是今天在某种僵尸模式中我无法弄明白。看起来像这样

<% var count = 0; var totalCount = 0; foreach (var item in Model)
   {
       count++; totalCount = Model.Count(); %>
<% if (count % 5 == 0 || count == 1) {%>
   <div class="row-me">
<%} %>

    <div>
        <h2>
            <%= item.Name %>
        </h2>
    </div>

    <% if (count % 4 == 0 || count == totalCount)
       {%>
         </div>
    <%} %>
<%  } %>

我希望它是

<div class="row-me">
<div></div>
<div></div>
<div></div>
<div></div>
</div>

2 个答案:

答案 0 :(得分:1)

你想要的条件是:

if ((count - 1) % 4 == 0)

示例:

(1 - 1) % 4 = 0
(2 - 1) % 4 = 1
(3 - 1) % 4 = 2
(4 - 1) % 4 = 3
(5 - 1) % 4 = 0
(6 - 1) % 4 = 1
(7 - 1) % 4 = 2
(8 - 1) % 4 = 3

答案 1 :(得分:0)

不是ASP程序员,但是你在循环顶部递增count这一事实可能会导致你的计算失败,特别是因为你使用的是模数。循环中count永远不会为零。尝试在循环的最后一行递增计数,你的模数应该更有意义。

未测试:

<% var count = 0; var totalCount = 0; foreach (var item in Model)
   {
       totalCount = Model.Count(); %>
<% if (count % 4 == 0) {%>
   <div class="row-me">
<%} %>

    <div>
        <h2>
            <%= item.Name %>
        </h2>
    </div>

    <% if (count % 4 == 0 || count == totalCount)
       {%>
         </div>
    <%} %>
<%  count++;
} %>

这应该是:

    <div class="row-me"><div><h2>...</h2></div></div>   <!-- count = 0 --> 
    <div><h2>...</h2></div>                             <!-- count = 1 --> 
    <div><h2>...</h2></div>                             <!-- count = 2 --> 
    <div><h2>...</h2></div>                             <!-- count = 3 --> 
    <div class="row-me"><div><h2>...</h2></div></div>   <!-- count = 4 --> 
    <div><h2>...</h2></div>                             <!-- count = 5 --> 
    <div><h2>...</h2></div>                             <!-- count = 6 --> 
    <div><h2>...</h2></div>                             <!-- count = 7 --> 
    <div class="row-me"><div><h2>...</h2></div></div>   <!-- count = 8 --> 

其中...item.Name

的输出