3

I am using Umbraco 7.x

I need some thing like following In list Item generated using for each. alternating item need to give respective class.

enter image description here

So is their any was to determine even and odd row to give respective class name.

As following is my code for the same.

@foreach (var itemTblRows in @Model.Children) 
        {       
         <tr class="light">
                <td>@itemTblRows.ABL_tableData1</td>
                <td>@itemTblRows.ABL_tableData2</td>
                <td>@itemTblRows.ABL_tableData3</td>
                <td>@itemTblRows.ABL_tableData4</td>
              </tr>
        }

I will not like to use CSS and JS to do so, because in other case (with diff. lay out) it will not work.

BJ Patel
  • 6,148
  • 11
  • 47
  • 81

3 Answers3

3

You can do easily with the IsOdd and IsEven helper methods:

<tr class="@itemTblRows.IsOdd("odd","even")>

or

<tr class="@itemTblRows.IsEven("even","odd")>
dampee
  • 3,392
  • 1
  • 21
  • 37
2

Here's a simple CSS only approach to accomplishing the result you're looking for. First, add a class to the table these rows belong to:

<table class="striped">
@foreach (var itemTblRows in @Model.Children) 
{       
   <tr>
        <td>@itemTblRows.ABL_tableData1</td>
        <td>@itemTblRows.ABL_tableData2</td>
        <td>@itemTblRows.ABL_tableData3</td>
        <td>@itemTblRows.ABL_tableData4</td>
   </tr>
}
</table>

Then add in these CSS rules:

table.striped tr:nth-child(even) { background-color: grey; }
table.striped tr:nth-child(odd) { background-color: white; }

Then you add in your CSS as needed. The nth-child(n) selector allows you to select every nth child that is a match. Specifying odd or even allows you take select every odd child, or every even child.

c0r3yz
  • 835
  • 8
  • 19
1

Create a counter variable c which you will increment in each loop. In each loop perform a modulus (%) using 2 as the denominator. If the result is greater than 0 then it is odd otherwise even

    var c = 1;
    @foreach (var itemTblRows in @Model.Children)
    {
        var oddEvenClass = c % 2 > 0 ? "odd" : "even";
        c += 1;
        <tr class="light @oddEvenClass">
            <td>@itemTblRows.ABL_tableData1</td>
            <td>@itemTblRows.ABL_tableData2</td>
            <td>@itemTblRows.ABL_tableData3</td>
            <td>@itemTblRows.ABL_tableData4</td>
        </tr>
    }
wingyip
  • 3,465
  • 2
  • 34
  • 52