有两种方法可以做到这一点,一种用于服务器绑定,另一种用于 ajax 绑定。
简单说明一下:我创建了一个名为“SmallItem”的模型,它只具有属性、CustomerID 和 OrdersQuantity(均为 int),因此如果对 SmallItem 进行任何引用,您就会知道它来自何处。
服务器:
这一切都可以通过声明 Telerik Grid 来实现:
@model IEnumerable<SmallItem>
@{Html.Telerik().Grid(Model)
.Name("TestGrid")
.Columns(columns =>
{
columns.Template(@<text>@(item.OrdersQuantity < 0 ? item.CustomerID.ToString() + "*" : item.CustomerID.ToString())</text>).Title("CustomerID");
columns.Bound(s => s.OrdersQuantity).Title("Order Quantity");
})
.CellAction(cell =>
{
if(cell.Column.Title == "CustomerID")
{
SmallItem item = cell.DataItem;
if(item.OrdersQuantity < 0)
{
cell.HtmlAttributes["style"] = "color: red;";
}
}
})
.Render();
}
正如您在上面看到的,我正在使用模板列,并使用 Razor 语法,只需设置一个简单的 if 语句即可在 CustomerID 字段旁边添加“*”。现在,更改单元格(而不是整行)属性的一种非常简单的方法是挂钩 CellAction 函数,该函数将为每个单元格执行。这里有一个简单的 if 语句来确保我们在 CustomerID 列中(注意使用 Title 而不是 Member,因为这是一个模板列),然后您可以检查 Model 的特定实例对 OrdersQuantity 有什么.如果它小于 0,只需将样式添加到 HtmlAttributes 集合。
阿贾克斯:
ajax 方法涉及使用一些 JavaScript,并且所有内容都可以在几行中涵盖。如果我的网格看起来像这样:
@{Html.Telerik().Grid<SmallItem>()
.Name("AjaxTestGrid")
.Columns(columns =>
{
columns.Bound(s => s.CustomerID).Title("Customer ID");
columns.Bound(s => s.OrdersQuantity).Title("Order Quantity");
})
.DataBinding(dataBinding => dataBinding.Ajax().Select("_Test", "Grid"))
.ClientEvents(clientEvents => clientEvents.OnRowDataBound("onRowDataBound"))
.Render();}
然后我可以利用 OnRowDataBound 事件,该事件为每一行触发。如果我使用这个 JavaScript:
function onRowDataBound(e) {
if (e.dataItem.OrdersQuantity < 0) {
e.row.cells[0].innerHTML += "*";
e.row.cells[0].style["color"] = "red";
}
}
我只是检查行的dataItem(只包含CustomerID和OrdersQuantity),看看我们的OrdersQuantity是否小于0,然后我只访问特定单元格的innerHTML和样式集合(因为CustomerID是第一列,它在索引 0)。
这两种方法都能满足您的需求,您实现哪一种仅取决于您绑定 Grid 的方式。