Alternating Item Styles In The ASP.NET ListView Control with jQuery

September 15th, 2008

In my last post I demonstrated how you could simply add alternating CSS styles to a ListView control without the need to duplicate your markup in an AlternateItemTemplate. This was accomplished through server-side code using the DataItemIndex to determine which style to apply. This time, we will look at how simple it is to apply the same effect using jQuery on the same simple markup that I used in the last post. I have removed the DataItemIndex related code and we are now left with this markup:

<asp:ListView ID="lvPeople" runat="server" ItemPlaceholderID="plcItem">
   <LayoutTemplate>
      <div id="people">
         <asp:PlaceHolder runat="server" ID="plcItem" />
      </div>
   </LayoutTemplate>
   <ItemTemplate>
      <div>
         First Name: <asp:Label runat="server" ID="lblFirstName" Text='<%# Eval("FirstName") %>' /><br />
         Last Name: <asp:Label runat="server" ID="lblLastName" Text='<%# Eval("LastName") %>' /><br />
         Age: <asp:Label runat="server" ID="lblAge" Text='<%# Eval("Age") %>' />
      </div>
   </ItemTemplate>
</asp:ListView>

With the markup in place, I have added a reference to the jQuery library in my page like so:

<script language="javascript" type="text/javascript" src="jquery-1.2.6.js"></script>

Now all that’s left is to add a little bit of jQuery code and we can apply our alternating css classes.

<script language="javascript" type="text/javascript">
   $(function() {
      $("div#people div")
         .filter(":even").addClass("even")
         .end().filter(":odd").addClass("odd");
   });
</script>

It’s that simple. The code listing above was broken out onto multiple lines, but could just as easily have been written in one single line, I prefer the format above for readability, but that’s just me.

The jQuery code selects all divs that are children of the wrapper div (identified with the “people” id attribute) and runs a filter that only returns the even items. It then adds a css class called “even” to those divs. The end() method then returns scope back to the first selection containing all of the child divs. The second filter runs just like the first, only this one returns the odd items and aplies the “odd” class to those divs.

If you haven’t used jQuery before, I suggest you check it out. It makes selecting items and then manipulating them simple and in a pretty intuitive way (IMHO). If you don’t think it looks easy, try writing code to do this without the aid of a JavaScript library such as jQuery, make it work across browsers and then decide if this way isn’t easier.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Andrew .NET, ASP.NET, JavaScript, jQuery , , ,

  1. No comments yet.
  1. No trackbacks yet.