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.

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

  • 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.

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

 

One Comment

Leave Reply