Search code examples
asp.net-mvcdynamicwebgrid

Adding dynamic class to Webgrid column from model property


I have a Webgrid with with many coloumn. One of the column is for due date. I need to change each entries color depending upon condition. Depending on condition i have added a color code property called "ColorCode" in view model. This color can be "red","yellow" or "green".

my DueDate column looks like:

 taskgrid.Column("DueDate", "Due Date", style: "DueDate", canSort: true, format: (item) => item.DueDate.ToShortDateString()),

here this coloumn has class "DueDate". I want to make it "DueDate red" , "DueDate yellow" or "DueDate green" from "item=>item.ColorCode" i.e:

style: "DueDate " + item=>item.ColorCode


Solution

  • The WebGrid helper doesn't support this. A possible workaround is to apply the style not on the <td> but on the item inside:

    taskgrid.Column(
        "DueDate", 
        "Due Date", 
        canSort: true, 
        format: 
            @<text>
                <div class="DueDate @item.ColorCode">
                    @item.DueDate.ToShortDateString()
                </div>
            </text>
    ),
    

    Other possible hacks involve using javascript to move the generated class from the inner <div> to the parent <td> if it's absolutely necessary for you to have this class applied on the <td>.