如何获得Kendo网格行选择

时间:2014-11-06 11:33:27

标签: jquery asp.net-mvc kendo-ui kendo-grid

如何启用kendo ui网格行选择。我通过使用html帮助函数创建了一个kendo网格,通过javascript访问它并启用了行选择,但下面没有显示运气代码

@(Html.Kendo().Grid((IEnumerable<Gridkendo.Models.Model>)Model)
  .Name("grid")
  .Columns(columns =>
  {
      // Create a column bound to the ProductID property
      columns.Bound(product => product.Name);
      // Create a column bound to the ProductName property
      columns.Bound(product => product.Description);

并在javascript

中访问它
<script>
    $(function () {
        // Notice that the Name() of the grid is used to get its client-side instance
        var grid = $("#grid").data("kendoGrid");
        var selectedItem = grid.dataItem(grid.select());
        alert(selectedItem.ShipName);
    });
</script>

1 个答案:

答案 0 :(得分:6)

您需要添加Selectable()配置方法。这将启用默认行选择

@(Html.Kendo().Grid((IEnumerable<Gridkendo.Models.Model>)Model)
  .Name("grid")
  .Columns(columns =>
  {
      // Create a column bound to the ProductID property
      columns.Bound(product => product.Name);
      // Create a column bound to the ProductName property
      columns.Bound(product => product.Description);
  })
  .Selectable()
)

注意您将在document ready事件中获取所选项目。这意味着网格刚刚初始化,并且不可能选择任何行。更好的方法是使用可在辅助器中配置的“select”事件:

@(Html.Kendo().Grid((IEnumerable<Gridkendo.Models.Model>)Model)
  .Name("grid")
  .Columns(columns =>
  {
      // Create a column bound to the ProductID property
      columns.Bound(product => product.Name);
      // Create a column bound to the ProductName property
      columns.Bound(product => product.Description);
  })
  .Selectable()
  .Events(ev => ev.Change("doOnRowSelect"))
)

然后,您需要定义doOnRowSelect JavaScript函数:

function doOnRowSelect(e) {
    var selectedItem = this.dataItem(this.select());
    alert(selectedItem.ShipName);
}

编辑:上述方法(至少是JavaScript部分)仅在通过AJAX加载数据时才有效。但是,当从Model加载数据时,行选择也应该起作用。在这种情况下,所选行将具有k-state-selected类:

function getSelectedItem () {
    var grid = $("#grid").data("kendoGrid");
    var selectedRows = $(".k-state-selected", "#grid");
    if (selectedRows.length > 0) {
       var selectedItem = grid.dataItem(selectedRows[0]);
       alert(selectedItem.ShipName);
    }
}
相关问题