asp.net mvc - Simplest way to provide alternate row styling in Razor
Asked Answered
D

6

11

Given the following Razor code:

<tbody>
    @foreach (Profession profession in Model)
    {
        <tr>
            <td>@profession.Name</td>
            <td>@profession.PluralName</td>
            <td>@Html.ActionLink("Edit", "AddOrEdit", new { Id = profession.ProfessionID })</td>
        </tr>
    }
</tbody>

What's the simplest way to provide some kind of alternate row styling? (i.e. different styling for odd and even rows.)

I don't seem to be able to add arbitrary C# to declare a bool variable which gets flipped each iteration of the foreach loop in order to set a classname for the tr, for example.

Dichotomize answered 28/10, 2011 at 9:44 Comment(0)
C
48

I'd recommend doing this in straight CSS (see here for more details):

tr:nth-child(odd)    { background-color:#eee; }
tr:nth-child(even)   { background-color:#fff; }
Cyrenaic answered 28/10, 2011 at 9:49 Comment(11)
This is CSS3. Not every browser supports it.Derisive
Indeed, and I was hesitant, but the question asked for the 'simplest way', and I believe this is.Cyrenaic
Modern browsers support it. And for legacy browsers there won't be alternating row color => not a big deal. People using legacy browsers are probably already accustomed to seeing differently rendered web sites on the internet.Disequilibrium
Yes, but depends who your audience are. In the industry I am in, most browsers are IE6.Derisive
@Aliostad, it looks very strange to me that an industry that can make an effort to use the latest technology from Microsoft to develop its web applications (ASP.NET MVC 3) is using a 3 generations old web browser. I mean IE6, really, this still exists?Disequilibrium
Welcome to UK NHS. 90% of browsers in UK NHS are IE6. Plan to migration to IE7 in 2012! They had applications built specifically for IE6 which only works in, well, IE6.Derisive
Plan to migration to IE7 in 2012. May God have mercy on your souls.Disequilibrium
Well, we have said they need to run the software in chrome frame, so theoretically I could be using tr:nth-child. But still favour broadest possible audience.Derisive
@Derisive - we write web apps for NHS people too. I feel your pain. But this one is just internal, so I can do all the CSS3 I like. Yay!Dichotomize
I'm giving this one the thumbs up because it works for me and it's the simplest solution.Dichotomize
Same goes for most of the pharma industry. 95% of our browser traffic is IE6.Hedi
D
11

JQuery can do that in the client side (and I would probably use client side scripting here rather than server logic).

 $("tr:odd").css("background-color", "#bbbbff");

You can also use just a simple variable to set the css class (almost pseudo-code):

@foreach (Profession profession in Model)
{
    @i++;
    <td class="@i%2==0?"even":"odd""> 

}
Derisive answered 28/10, 2011 at 9:48 Comment(1)
To avoid complaints from visual studio use brackets, e.g. <tr class="@(i%2==0? "":"alt")">Botzow
M
3

There's a lot of ways as other proposed. From my point, this wouldn't be the simplest but a bit easier:

<tbody>
    @var oddEven = new List { "odd", "even" };
    @var i = 0;
    @foreach (Profession profession in Model)
    {
        <tr style="@oddEven[i++ % 2]">
            <td>@profession.Name</td>
            <td>@profession.PluralName</td>
            <td>@Html.ActionLink("Edit", "AddOrEdit", new { Id = profession.ProfessionID })</td>
        </tr>
    }
</tbody>
Madlin answered 28/10, 2011 at 10:2 Comment(0)
S
2

Apologies that this is a slightly obtuse answer as you're already doing the mark-up, but as your table looks pretty standard you could switch to using the Mvc Web Grid Helper. It's a neat tool for tables like this. I think your code would be slightly shorter / simpler for this particular table, and the actual implementation of the alternating row style would be very simple:

alternatingRowStyle: "alternateRow"

More info on this asp.net blog.

Schoolman answered 28/10, 2011 at 10:16 Comment(1)
I like the idea of this control but it would take quite a lot more work than some of the other solutions. Thanks for the link though.Dichotomize
R
1

Since you are using MVC Razor utilizing the @helper function is the simplest, cleanest and best approach.

In the App_Code folder of your project add new item or modify your existing CustomeHelpers.cshtml file with the following code:

@helper AlternateBackground(string color, Int32 iViewBagCount) {
    if (iViewBagCount == null) { iViewBagCount = 0; }
    <text>style="background-color:@(iViewBagCount % 2 == 1 ? color : "none")"</text>
    iViewBagCount++;
}

Then on your view, inside your foreach loop, replace the tablerow code with what's shown below:

<tr @CustomHelpers.AlternateBackground("#ECEDEE", ViewBag.count)>

or

<tr @CustomHelpers.AlternateBackground("Red", Model.Count())>

Whichever is appropriate for your foreach loop

This way you only have to add the @Helper function once and it propagates throughout your application and it can be called on each view as needed by referencing the @CustomHelpers function. Create as many helpers as you need and call them with the @CustomeHelpers.NameOfYourFunction() and go from there.

Simple and effective...

Roeder answered 24/2, 2016 at 21:49 Comment(0)
B
0

Found this while googling, so I think it's worth it replying for anyone else who might chance upon this. Nowadays, you can just use bootstrap, and do this, voila!

<table class="table table-striped">
Brinkley answered 1/9, 2024 at 18:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.