2011-10-18 42 views
1

我試圖用剃刀輸出一個HTML表。表本身的工作,但現在我想一個名爲「甚至」類添加到所有其他行的表:ASP.NET MVC Razor - 如果裏面的

<table> 
    <thead> 
     <tr> 
      <th>Column 1</th> 
      <th>Column 2</th> 
      <th>Column 3</th> 
     </tr> 
    </thead> 
    <tbody> 
     @for (int i = 0; i < ViewBag.MyList.Count; i++) 
     { 
      var myObject = ViewBag.MyList[i]; 
      <tr @if (i % 2 == 0) { class="even" }> 
       <td>myObject.Column1</td> 
       <td>myObject.Column2</td> 
       <td>myObject.Column3</td> 
      </tr> 
     } 
    </tbody> 
</table> 

有明顯有毛病的循環中,如果情況,但什麼是寫這個的正確方法?

回答

11
<table> 
    <thead> 
     <tr> 
      <th>Column 1</th> 
      <th>Column 2</th> 
      <th>Column 3</th> 
     </tr> 
    </thead> 
    <tbody> 
     @for (int i = 0; i < ViewBag.MyList.Count; i++) 
     { 
      var myObject = ViewBag.MyList[i]; 
      <tr @{if (i % 2 == 0) { <text>class="even"</text> }}> 
       <td>myObject.Column1</td> 
       <td>myObject.Column2</td> 
       <td>myObject.Column3</td> 
      </tr> 
     } 
    </tbody> 
</table> 

請看看通過菲爾哈克剃刀語法快速參考

http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx

和Scott guthries張貼關於您的問題

http://weblogs.asp.net/scottgu/archive/2010/12/15/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax.aspx

+0

謝謝dknaack,工作正常!並感謝您的鏈接。 :) – haagel

2

爲什麼不直接使用CSS3斑馬條紋你的表?

tr:nth-child(2n+1) { 
    background-color: #99ff99; 
}