46

In MVC3, how do you create alternating row colors on a @foreach list when using the Razor view engine?

@foreach (var item in Model) {    
    <tr>
        <td>@item.DisplayName</td>
        <td>@item.Currency</td>
        <td>@String.Format("{0:dd/MM/yyyy}", item.CreatedOn)</td>
        <td>@String.Format("{0:g}", item.CreatedBy)</td>
        <td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
    </tr>
}
3
  • 2
    One year on, and with so many views I had to change the accepted answer. CSS is the correct way to do this, not code.
    – JK.
    Jan 3, 2012 at 12:07
  • 6
    @trebormf's answer is dependent on JavaScript. The most upvoted answer (@Kirk Woll) will accomplish the same thing but without a dependency on JavaScript. This will make it compatible with more clients, lighter weight and faster rendering - IMHO "more correct". The originally selected answer DOES use CSS. It was inline CSS, but CSS none-the-less. You could change it to set a class name or something instead of inline CSS.
    – BenSwayne
    Apr 23, 2012 at 3:46
  • 2
    CSS is the right way to apply the styles. However rendering a table and then changing it in the DOM using JQuery is still code: just not your code. I suspect if you do performance timings on page generation you'll find the server-based approach is faster, and not reliant on JS
    – Quango
    Mar 9, 2013 at 16:22

14 Answers 14

56

Assuming you would rather not use CSS (i.e. :nth-child(odd)) you can either:

  • use a normal for loop:

    @for (int i = 0; i < Model.Count; i++)
    {
        ...
    }
    
  • use .Select:

    @foreach (var item in Model.Select((x, i) => new { Data = x, Index = i }))
    {
        ...
    }
    

Either way, you'd have access to the current index and could then use i % 2 == 1 as the condition for your background-color. Something like:

<tr style="background-color:@(i % 2 == 1 ? "red" : "white")">...</tr>
2
  • Nearly one year after accepting, I've changed my mind - its not correct to do a pure UI styling task in code. CSS is the correct way to go and accepted trebormf's answer instead
    – JK.
    Jan 3, 2012 at 12:05
  • 22
    @JK., out of curiosity, did you ignore the first sentence in my answer?
    – Kirk Woll
    Jan 3, 2012 at 20:10
42

This is what CSS is for (changing style rather than content). Save the server the effort: Do it on the client.

Since you're using Razor, you can use JQuery. Here's how I do it in my projects:

$(document).ready(function () {
    $("table > tbody tr:odd").css("background-color", "#F7F7F7");
}
4
  • 2
    +1 This is actually the correct way to go. I use it for any alternating item table now. Except that I use .addClass() instead of .css(). Changed accepted answer to this one.
    – JK.
    Jan 3, 2012 at 12:06
  • Thanks, JK. I took took a chance answering your question 3 months later even though you had already accepted an answer. I appreciate it.
    – trebormf
    Jan 4, 2012 at 20:57
  • 19
    "Since you're using Razor, you can use jQuery." - What does that even mean? They're independent of each other.
    – David East
    Jun 20, 2012 at 17:38
  • 3
    It was not the best choice of words on my part. The MVC3/Razor project templates include jQuery. You're right, they are not inextricably linked.
    – trebormf
    Aug 3, 2012 at 17:04
25

With ASP.NET MVC 3 and the new @helper syntax, there is a neater way to handle this.

First add this @helper method:

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

Then just add the call to the helper in your <TR> element

@foreach (var item in Model) {    
    <tr @AlternateBackground("Red")>
        <td>@item.DisplayName</td>
        <td>@item.Currency</td>
        <td>@String.Format("{0:dd/MM/yyyy}", item.CreatedOn)</td>
        <td>@String.Format("{0:g}", item.CreatedBy)</td>
        <td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
    </tr>
}
3
  • nicely done! Little formatting error it should be <tr @AlternateBackground("Red")>. It won't work right without the '@'
    – Rondel
    Nov 16, 2011 at 22:20
  • This helped me out tremendously dealing with HTML e-mails. As you may know CSS <style> tags are stripped by some e-mail (em, GMail), and CSS is mangled in other e-mail (em, Outlook). I set up nice zebra striping with CSS' nth thingy, but was smacked hard by the HTML e-mail beast. Using MVC3 this helped tremendously to putting the striping back in my long tables. YAY! Just have to add the @ to every <tr> (BOO?).
    – REMESQ
    Aug 3, 2012 at 21:46
  • What a brilliant answer. Now with this I no longer need a table. I am using it for a panel.
    – user2537701
    Jan 11, 2015 at 22:56
22

You could always do it in pure css using:

TABLE.test tr:nth-child(even)
{
    background-color: #EFEFEF;
}
3
  • this is the more elegant solution, imho. Thanks!
    – Vinzz
    Mar 9, 2012 at 13:44
  • Yes, I second that. For me, this is the best solution. Thanks.
    – sammydc
    Feb 21, 2013 at 1:59
  • +1, elegant syntax. However, you should always mention browser support when doing anything fancy with css. In this case, no support in IE prior to version 9.
    – Patrick M
    Sep 30, 2013 at 22:01
9

How about something like this?

@for (int i = 0; i < Model.length; i++) {
  <tr @(i % 2 != 0 ? class="odd" : "")>
    <td>@Model[i].DisplayName</td>
    <td>@Model[i].Currency</td>
    <td>@String.Format("{0:dd/MM/yyyy}", Model[i].CreatedOn)</td>
    <td>@String.Format("{0:g}", Model[i].CreatedBy)</td>
    <td>@Html.ActionLink("Edit", "Edit", new { id = Model[i].Id })</td>
  </tr>
3
  • it's IEnumerable, so @for didn't work, and there was something wrong with <tr @(i % 2 != 0 ? class="odd" : "")> too
    – JK.
    Feb 8, 2011 at 6:53
  • line 2 might be better as <tr class="@(i%2 != 0 ? "odd" : null)" >
    – Quango
    Mar 9, 2013 at 16:20
  • @Quango: Yes, in the version of Razor that ships with MVC4+, that's a better way to do it (that leaves class="" (or would it be class=null?) in MVC3's Razor engine though, which is kind of sloppy).
    – Dave Ward
    Mar 9, 2013 at 18:19
5
@{  
    int i = 0;
    foreach (Account acct in Model)
    {
        <div class="row @(i%2==0?"even":"odd")">     
            <a href="/Account/Details/@acct.id">@acct.name</a>
        </div>
        i++;
    }
}
3

Original: http://15daysofjquery.com/table-striping-made-easy/5/ Author: Jack Born jQuery Zebra_Striping_Made_Easy

=============== Java script ===================

$(document).ready(function () {
          $('.stripeMe tr:even').addClass('alt');

          $('.stripeMe tr').hover(
            function () {
                $(this).addClass("highlight");
              },
             function () {
                $(this).removeClass("highlight");
              });
      });

================= css =================

tr.alt td {
background-color : #F7F7F7;
}
tr.highlight td {
background-color : #bcd4ec;
}

=============== HTML ===============

<table class="stripeMe">
1
  • I Like this to dynamically attach a class value
    – Diin
    Feb 10, 2013 at 16:48
2

There isn't much documentation on it, but the Loop Helper (http://nuget.org/Packages/Packages/Details/Loop-Helper-for-WebMatrix-0-1) gives you support for detecting Even/Odd/etc. items.

1
  • Thanks I will try that too - @anurse since you would have to be the most authoritative source for razor answers :)
    – JK.
    Feb 8, 2011 at 22:23
1

What you can do is to set a variable odd outside of the foreach()

@{
    var odd = false;
}

And then, inside your foreach loop, you'd change the value of it and then use it in an if condition to set the alternating classes.

@foreach (var item in Model) {
    odd = !odd;

    <tr class="@(odd ? "odd" : "even")">
        <td>@item.DisplayName</td>
        <td>@item.Currency</td>
        <td>@String.Format("{0:dd/MM/yyyy}", item.CreatedOn)</td>
        <td>@String.Format("{0:g}", item.CreatedBy)</td>
        <td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
    </tr>
}
1

An old post, but none of the answers covered this approach, so I will.

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 your foreach loop would look like this:

@foreach (var item in Model) {    
    <tr @CustomHelpers.AlternateBackground("#ECEDEE", Model.Count())>
        <td>@item.DisplayName</td>
        <td>@item.Currency</td>
        <td>@String.Format("{0:dd/MM/yyyy}", item.CreatedOn)</td>
        <td>@String.Format("{0:g}", item.CreatedBy)</td>
        <td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
    </tr>
}

You can pass a color identifier like "#ECEDEE" or the named color "Blue".

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.

0

what about using the jQuery DataTable plugin. i used it on an MVC2 application i developed.

http://www.datatables.net/

0

A solution i use to support IE8 (corporate browser, not by choice) was to combine the_lotus's solution with a jquery solution

Since IE8 doesnt support nth-child() use this css

.tableclass tr.even{
    background:#E6EDF5;
}

And use jQuery to do this:

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

You could let the framework decide how best to render it, presumably using a bit of browser detection logic and whatever other goodness it has built-in, something like the following, and get on with your life.

:-)

My point being that with this approach the WebGrid will control the alternating grid colors using the best technology it can (best that it is designed to use, at least) for the detected browser. It might not use "nth" CSS syntax, but that might not work for all of your intended audience, anyway, so you'd have to detect the browser and emit different content on your own. Of course everybody should be using a CSS 3.x-compliant browser by now, but mileage varies.

@myWebGrid.GetHtml
    (
    tableStyle: "some-style",
    headerStyle: "some-head-style",
    alternatingRowStyle: "some-fancy-alt-row-style",
    etc ...
    )

The System.Web.Helpers.WebGrid's GetHtml method signature looks like this here:

public IHtmlString GetHtml
    (
    string tableStyle = null,
    string headerStyle = null,
    string footerStyle = null,
    string rowStyle = null,
    string alternatingRowStyle = null,
    string selectedRowStyle = null,
    string caption = null,
    bool displayHeader = true,
    bool fillEmptyRows = false,
    string emptyRowCellValue = null,
    IEnumerable<WebGridColumn> columns = null,
    IEnumerable<string> exclusions = null,
    WebGridPagerModes mode = WebGridPagerModes.Numeric | WebGridPagerModes.NextPrevious,
    string firstText = null,
    string previousText = null,
    string nextText = null,
    string lastText = null,
    int numericLinksCount = 5,
    object htmlAttributes = null
    );
0

@helper Prop(List prop) { foreach (var p in prop) { p } }

format: @Prop(@item.Prop)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.