Reputation: 4052
I am using a <% foreach ...%> loop to list a collection of items on my website.
I want to add a different background color for the style of alternating rows in my list. I have found a way to do this but I am not satisfied with it as it seems like 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 a best practice that I am missing that people are using for this scenario in ASP.NET MVC?
Upvotes: 7
Views: 2641
Reputation: 16411
If you don't want to use a class you can set css directly with jquery.
Suppose your table tag is: <table id="tb">...
, you just have to set your 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>
Upvotes: 1
Reputation: 13571
If you are the daring types who wants to dive into CSS3
tr:nth-child(odd) { background-color:#eee; }
tr:nth-child(even) { background-color:#fff; }
Upvotes: 5
Reputation: 5813
If you want it cleaner I'd recommend writing a custom HtmlHelper
extension. I would not use jquery as stu42 suggests simply because I like to look to javascript purely for behavior. Ideally, and hopefully in the not too distant future, you would use pure css for this purpose. Until then, I'd leave it in the markup, as you're currently doing, but with an extension that handles the logic, pulling it out of the aspx.
Upvotes: 1
Reputation: 4052
I found this snippet of JQuery code, which I find to be much cleaner.
$(document).ready(function() { $("table tr:nth-child(odd)").addClass("colorfull"); });
I have taken out the counter logic. This JQuery script manipulates the DOM to set the css class of every other row in the foreach loop.
Upvotes: 12