Dynamically set row background color in a WebGrid depending on the content

I created an exercise log with a grid showing the week results with a background color indicating if the week is in the future (white), failed (red) or was an epic success (green). The WebGrid does not support this out of the box at the moment. I looked over different alternatives to solve this.

  • Knockout can trigger actions on table rows directly or via MVC Controls Toolkit.
  • Render the table on my own instead of using the WebGrid.
  • Use jQuery to set the background colors at the $(document).ready()

 

Solution

I choose the last alternative out of curiosity. My solution is a variant of this SO thread where I don’t show a column for the value deciding the background color.

The property SuccessColor in my view model  TrainingWeek contains the background color to present for the week. Use the following code in the view to define a grids week number column.

trainingGrid.Column("WeekNumber", "Vecka", (item) => Html.Raw(string.Format("<div class='color' style='display: none;'>#" + item.SuccessColor + "</div><center><text>" + item.WeekNumber + "</text></center>")))

Finally use the following script to set grid row background colors depending on the weeks SuccessColor

$(document).ready(
    function () {
        $('.grid .color').each(function (index, element) { $(element).parent().parent().css('background-color', $(element).html()); });
    }
);

 

Trackback URL: https://codeblog.silfversparre.com/2011/11/dynamically-set-row-background-color-in-a-webgrid-depending-on-the-content/trackback/