偶数和奇数表行与Razor

Jac*_*ius 12 razor asp.net-mvc-3

我正在使用带有MVC 3的Razor视图引擎,我试图使偶数行和奇数行在表中具有不同的类.

到目前为止我已经有了这个

@{ var odd = true; }
@foreach(var userLot in Model) {
    if (!odd) {
        <tr id="lot@userLot.Id" class="even">
    else
        <tr id="lot@userLot.Id" 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; }
}
Run Code Online (Sandbox Code Playgroud)

这给我带来了无穷无尽的麻烦,愚蠢的视图引擎无法弄清楚什么是标记和什么是代码.我已经尝试在文本指令中包装tr开口标记,但是然后愚蠢的视图引擎呻吟着关闭tr标签.如果我然后将结束tr标记包装在text指令中,那么愚蠢的视图引擎就会怀疑text指令没有开始标记.

要明确一点,这个

<text></ tr></text>
Run Code Online (Sandbox Code Playgroud)

给出错误,文本标记没有匹配的开始标记.可爱.

我怎么写这个,以便Razor不会出错?

请不要推荐JavaScript解决方案,我试图解决Razor问题.

Mik*_*erg 30

这个怎么样:

@{ var odd = true; }
@foreach(var userLot in Model) {
   <tr id="lot@(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;
}
Run Code Online (Sandbox Code Playgroud)

@( ... ) 是一个有效且非常有用的陈述.

  • 一旦你处于代码中,就不需要`@ {..}`,这有时会让人感到困惑. (2认同)