how to get Kendo grid row selection

21,241

You need to add the Selectable() configuration method. This will enable the default row selection,

@(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()
)

Note that you are getting the selected item in the document ready event. This means that the grid has just been initialized and it's improbable that any row had been selected. A better approach is to use the "select" event, configurable in the helper:

@(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"))
)

You then need to define the doOnRowSelect JavaScript function:

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

EDIT: the method above (at least the JavaScript part) works only when the data is loaded trough AJAX. The row selection however should also work when the data is loaded from the Model. In this care, the selected row will have the k-state-selected class:

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);
    }
}
Share:
21,241
peter
Author by

peter

Updated on November 07, 2020

Comments

  • peter
    peter over 3 years

    How to enable kendo ui grid row selection .I created a kendo grid by using html helper function accessed it via javascript and enabled row selction ,but no luck code is shown below

    @(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);
    

    and accessed it in 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>