【问题标题】:Webmatrix - WebGrid: change css style conditionallyWebmatrix - WebGrid:有条件地更改 CSS 样式
【发布时间】:2013-07-31 16:36:56
【问题描述】:

我刚开始使用 Webmatrix,我正在尝试将 HTML 表格转换为 webgrid。 数据来自数据库,我想根据项目内容更改每个 td(在一列内)的 css 类。

例如,如果项目包含“,”,则应用 class="multi",如果不包含“,”且不为空,则应用 class="single",否则应用“none”。

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

我已经尝试使用 webgrid style:format: 设置,但我无法根据项目的值切换类名。我想我只需要正确的语法就可以开始了。

我希望你能在这里帮助我。 谢谢。

【问题讨论】:

    标签: asp.net razor webmatrix webgrid


    【解决方案1】:

    如果你想使用 WebGrid,你唯一真正的选择是在渲染后通过 Javascript 根据单元格值设置td 样式。 style 参数只接受代表要应用的 CSS 类的字符串。

    或者,您可以根据值有条件地设置format 参数中的内容,用spandiv 填充div,然后您可以设置样式,例如:

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

    更新:以下代码说明了格式参数中包含的更复杂的 if..else 语句:

    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>
    

    【讨论】:

    • 感谢您提供代码示例 - 但是我无法让它工作。我必须使用像 Contains() 这样的方法,但我不知道如何在 razor 中使用它。
    • 其实代码部分是标准的C#,所以你照常应用。我已经更新了我的回复以包含一个代码示例,该示例显示了您的逻辑如何被容纳。它需要调整,因为我不知道您的项目的属性名称或您实际想要对 css 样式做什么。
    猜你喜欢
    • 2012-09-11
    • 1970-01-01
    • 2013-07-07
    • 2015-09-15
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多