Even and odd table rows with Razor

asp.net-mvc-3razor

I'm using the Razor view engine with MVC 3 and I'm trying to make even and odd rows have different classes in a table.

So far I've got this

@{ 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; }
}

This is giving me endless trouble with the stupid view engine unable to figure out what is markup and what is code. I've tried wrapping the tr opening tags in a text directive, but then the stupid view engine moans about the closing tr tags. If I then wrap the closing tr tag in a text directive the stupid view engine moans that the text directive has no opening tag.

Just to be clear, this

<text></ tr></text>

gives an error that the text tag has no matching opening tag. Lovely.

How do I write this so that Razor doesn't give an error?

Please don't recommend a JavaScript solution, I'm trying to get around the Razor issues here.

Best Answer

How about this:

@{ 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;
}

@( ... ) is a valid and very useful statement.