2

How can I extend this List template razor delegate example that Phil Haack mentions here, so that I can provide an alternate row css class?

http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx

I would like to do something similar to this:

@comics.List(
  @< tr class="@odd">
    < td>@item.Title< /td>
    < td>@item.Publisher< /td>
  )

Edit: I don't need a javascript or css solution. I need to be able to support older browsers and browsers that may have javascript disabled.

Paul Tyng
  • 7,924
  • 1
  • 33
  • 57
Victor
  • 4,989
  • 6
  • 31
  • 47

2 Answers2

3

If you must have a server side solution, something like this will do it:

@{ var odd = false; }

@comics.List(
    @<tr class="@((odd = !odd) ? "odd-row" : "")">
        <td>@item.Title</td>
        <td>@item.Publisher</td>
  )

It should result in:

<tr class="odd-row">
<tr class="">
<tr class="odd-row">

The (odd = !odd) is a boolean test plus a NOT operation that toggles the flag.

Paul Tyng
  • 7,924
  • 1
  • 33
  • 57
2

I assume using just CSS would also solve your stated problem:

tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}


Update of my answer after your Edit

I was not familiar with this Razor templating mechanism, thanks for sharing, anyway I read up on it to understand it better.

Unfortunately it does not seem possible. As the underlying HelperResult expects a single parameter named @item and more parameters cannot be added. This article explains the issue clearly.

I guess it is possible write a specific table template using thistechnique and achieve your desired result but IMHO the foreach route is simpler.

Philip Fourie
  • 111,587
  • 10
  • 63
  • 83
  • 1
    +1 CSS is the easiest way to achieve the requirement. Would something like this be any good to you? http://stackoverflow.com/questions/267033/getting-odd-even-part-of-a-sequence-with-linq – Nick Ryan Feb 20 '12 at 15:50
  • Thanks for the link Nick. That won't help me build up a list or alternating rows. I know how to achieve alternate rows using a simple foreach loop, I'm looking to create something with very easy to use syntax, like the Template Razor Delegates example I posted. – Victor Feb 20 '12 at 16:02