【问题标题】:Telerik MVC Grid making a Column Red Color based on Other Column ValueTelerik MVC Grid 根据其他列值制作红色列
【发布时间】:2011-10-28 23:46:43
【问题描述】:

我有一个 Telerik MVC 网格,其中有两个字段

CustomerIDOrdersQuantity (can go negative)

我的网格是这样的

CustomerID                 OrdersQuantity

1                               10 
2                                3  
<font color="red">4*</font>    -10 
<font color="red">5*</font>    -20 
7                               10  

我想以红色显示customerid,如果OrdersQuantity is &lt; 0,则添加"*" SYMBOL

就像上面的例子一样,我想用红色显示 customerid 4*5*

【问题讨论】:

    标签: telerik telerik-mvc


    【解决方案1】:

    有两种方法可以做到这一点,一种用于服务器绑定,另一种用于 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 的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      相关资源
      最近更新 更多