我刚刚开始使用Webmatrix,我正在尝试将HTML表格转换为webgrid。 数据来自数据库,我想根据项目内容更改每个td(在一列中)的css类。
因此,例如,如果项目包含“,”则应用class =“multi”,如果它不包含“,”并且不为null,则class =“single”,否则为“none”。
<td class="multi">
<td class="single">
<td class="none">
我已尝试使用webgrid 样式:和格式:设置但我无法根据项目的值来切换类名。我想我只需要正确的语法就可以开始了。
我希望你能在这里帮助我。 谢谢。
答案 0 :(得分:2)
如果您想使用WebGrid,您唯一真正的选择是在呈现后通过Javascript基于单元格值设置td
样式。 style
参数只接受表示要应用的CSS类的字符串。
或者,您可以根据值有条件地设置format
参数中的内容,并使用td
或span
填充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>