Search code examples
asp.netrazorwebmatrixwebgrid

Webmatrix - WebGrid: change css style conditionally


I've just started with Webmatrix and I'm trying to transform an HTML table to the webgrid. The data comes from the DB and I want to change the css class for each td (within one column) depending on the items content.

So for example if the item Contains "," then apply class="multi", if it doesn't contain "," and is not null then class="single", else "none".

<td class="multi">
<td class="single">
<td class="none">

I've tried it with the webgrid style: and format: settings but I couldn't get the classname to switch depending on the value of the item. I think I just need the right syntax to get started.

I hope you can help me out here. Thank you.


Solution

  • If you want to use the WebGrid, your only real option is to set the td style based on the cell value via Javascript after it has rendered. The style parameter will only accept a string representing the CSS class to apply.

    Alternatively, you can conditionally set the content in the format parameter based on the value, filling the td with a span or div that you can then style eg:

    <style>
        td.nopadding{padding: 0;margin: 0;}
        .green{background-color:green;display: inline-block;width: 100%;height: 100%;}
        .yellow{background-color:yellow;display: inline-block;width: 100%;height: 100%;}
    </style>
    <div id="grid">
        @grid.GetHtml(    
            tableStyle : "table",
            alternatingRowStyle : "alternate",
            headerStyle : "header",
            columns: grid.Columns(
                grid.Column("Country", style: "nopadding", format: @<text>@Html.Raw(item.Country == "USA" ? 
                                                                     "<span class=\"green\">" + item.Country +"</span>" : 
                                                                     "<span class=\"yellow\">" + item.Country +"</span>")</text>))
        )
    </div>
    

    UPDATE: The following code illustrates a more complex if..else statement being accommodated in the format parameter:

    format: @<text>@if(item.YourProperty == null){
                      @Html.Raw("<span class=\"none\">" + some_value +"</span>")
                      }
                      else{
                        if(item.YourProperty.Contains(",")){
                             @Html.Raw("<span class=\"multi\">" + some_value +"</span>")
                        }
                        else{
                            @Html.Raw("<span class=\"single\">" + some_value +"</span>")
                        }
                   }
                   </text>