How to style alternating lines in asp.net mvc

I use the <% foreach ...%> loop to list a collection of elements on my website.

I want to add a different background color for the style of alternating lines in my list. I found a way to do this, but I am not happy with this, as it seems to be a hack.

Here is what I have done to solve it so far:

<table> <% int counter = 0; foreach (var item in Model) { counter++; if (counter % 2 == 0) { %> <tr class="colorfull"> <% } else { %> <tr> <% } %> ... 

Is there any best practice that I skip that people use for this script in ASP.NET MVC?

+7
jquery html stylesheet asp.net-mvc
source share
4 answers

I found this piece of jQuery code that I find much cleaner.

 $(document).ready(function() { $("table tr:nth-child(odd)").addClass("colorfull"); }); 

I took out the logic of the counter. This jQuery script controls the DOM to set the css class for every other line in the foreach loop.

+12
source share

If you are bold types who want to dive into CSS3

 tr:nth-child(odd) { background-color:#eee; } tr:nth-child(even) { background-color:#fff; } 
+5
source share

If you want it cleaner, I would recommend writing a custom HtmlHelper extension. I would not use jquery since stu42 offers just because I like to look at javascript solely for behavior. Ideally, and hopefully in the near future you would use pure css for this purpose. Until then, I would leave it in the markup, as you are doing now, but with an extension that processes the logic, pulling it out of aspx.

+1
source share

If you do not want to use the class, you can directly install css using jquery.

Suppose your table tag is: <table id="tb">... , you just need to install html as follows:

 <head> <script language="javascript" type="text/javascript" src="jquery-min.js"/> </head> <body> <script language="javascript" type="text/javascript"> $(document).ready(function() { $("#tb tr:odd").css("background-color", "#F4F4F8"); }); </script> <table id="tb"> <tr><th>Id</th><th>Name</th></tr> <tr><td>1</td><td>Junior</td></tr> <!--more rows here... --> </table> </body> 
+1
source share

All Articles