2011-03-17 60 views
11

我使用MVC 3 Razor視圖引擎,我試圖使偶數行和奇數行在表中有不同的類。偶數和奇數表格行與剃刀

到目前爲止,我已經有了這個

@{ var odd = true; } 
@foreach(var userLot in Model) { 
    if (!odd) { 
     <tr id="[email protected]" class="even"> 
    else 
     <tr id="[email protected]" class="odd"> 
    }  
      <td>@userLot.Id</td> 
      <td>@userLot.Description</td> 
      <td>@userLot.Carat</td> 
      <td class="averageBid">@userLot.AverageBid</td> 
      <td class="rank">@userLot.Rank</td> 
      <td class="currentBid">@userLot.CurrentBid</td> 
      <td style="width: 200px; height: 30px;" class="tdWithBidInput"><input type="text" style="display: none" /></td> 
     </tr> 
    @{ odd = !odd; } 
} 

這讓我無法弄清楚什麼是標記的,什麼是代碼愚蠢的視圖引擎無盡的煩惱。我已經嘗試在文本指令中包裝tr開放標籤,但隨後愚蠢的視圖引擎呻吟了關閉tr標籤。如果我然後將close tr標籤包裝在文本指令中,那麼愚蠢的視圖引擎會呻吟文本指令沒有開始標籤。

只是要清楚,這

<text></ tr></text> 

給出了一個錯誤,該文本標籤沒有與之匹配的標籤。可愛。

我該如何寫這個讓Razor不會給出錯誤?

請不要推薦JavaScript解決方案,我試圖在這裏解決Razor問題。

+1

另請參閱http://stackoverflow.com/questions/4929538/c-sharp-mvc3-razor-alternating-items-in-a-foreach-list – 2012-08-20 18:38:16

回答

26

如何:

@{ var odd = true; } 
@foreach(var userLot in Model) { 
    <tr id="[email protected](userLot.Id)" class="@(odd ? "odd": "even")"> 
     <td>@userLot.Id</td> 
     <td>@userLot.Description</td> 
     <td>@userLot.Carat</td> 
     <td class="averageBid">@userLot.AverageBid</td> 
     <td class="rank">@userLot.Rank</td> 
     <td class="currentBid">@userLot.CurrentBid</td> 
     <td style="width: 200px; height: 30px;" class="tdWithBidInput"><input type="text" style="display: none" /></td> 
    </tr> 
    odd = !odd; 
} 

@(...)是一個有效的和非常有用的聲明。

+0

嗯....這解決了第一個問題,但現在它呻吟在@ {odd =!odd; } - 我得到的錯誤是方法沒有超載'寫'需要0個參數 – 2011-03-17 08:50:28

+2

當你在代碼中時,你不需要'@ {..}'「,這有時會令人困惑。 – 2011-03-17 08:53:35

+0

heh好像我們在同一時間編輯 – 2011-03-17 08:54:14