Search code examples
.netcssrepeatermoduloitemtemplate

How can I get alternate styling in <ItemTemplate> (.NET)?


I'm using EPiServer for this website. Unlike asp:DataList, EPiServer:PAgeList does not have AlternatingItemTemplate.

So I need to create a counter and increase this counter in my <ItemTemplate>, and then use modulus to return whuch css style to append to article / page.

Modulus "code" - fromcode behind:

 return index % 2 == 0 ? "styleA" : "styleB";

But I'm not abler to ad an counter and increase this in the <ItemTemplate>.

Any suggestions much appreciated!

UPDATE
Here is my EPiServer Page List controller:

 <EPiServer:PageList runat="server" id="pageList" SortDirection="Ascending" Count="4" OnDataBinding="pageList_OnDataBinding">
    <HeaderTemplate>
        <ul id="articleList1">
    </HeaderTemplate>

    <ItemTemplate>
            <li>
                   <h2><a href="<%# Eval("LinkURL") %>" title="<%# Eval("PageName") %>"><EPiServer:Property id="Property1" PropertyName="PageName" runat="server" /></a></h2>
                   <div class="articleImage">
                      <%# ArticleImage(Container.CurrentPage)%>                            
                   </div>
                   <div class="introText">
                      <%# IntroText(Container.CurrentPage)%> 
                   </div>
                   <div class="readMore floatRight"><a href="<%# Eval("LinkURL") %>" title="<%# Eval("PageName") %>">Les mer</a></div>
            </li>
    </ItemTemplate>

    <FooterTemplate>
        </ul>     
    </FooterTemplate>
 </EPiServer:PageList> 

ANSWER
I decided that using jQuery was a LOT simpler than hacking around with .NET. It's not my preferred solution, but it works. The code I use is this:

if (jQuery("#articleList1").length > 0) {
    jQuery('li:odd').addClass("odd");
}

Solution

  • For a repeater I do this:-

    <itemtemplate>
    <tr class='<%#(Container.ItemIndex % 2 == 0) ? "odd" : "even" %>'>
    

    EDIT for an on item databound event keep a track of the row counter...

    private int counter;
    protected void list_databound(object sender, RepeaterItemEventArgs e)
        {
         if ((e.Item.ItemType == ListItemType.Item) || ((e.Item.ItemType == ListItemType.AlternatingItem))
         {
          counter++;
          //find server control and use counter as modulus
         }
        }
    

    Edit here you go... OOPS needed to be a HtmlTableRow!!

    HtmlTableRow row = e.Item.FindControl("row") as HtmlTableRow;
    if (row != null) 
      row.Attributes.Add("class", ((counter % 2 == 0) ? "odd": "even") );
    

    you will also need this

    <tr id="row" runat="server" ...