How to get selected row and its DataItem

4 Answers 23762 Views
Grid
Indy
Top achievements
Rank 1
Indy asked on 10 Mar 2014, 03:45 PM
How do I get the grid's selected row and its DataItem.?

After searching around since I couldn't find any sample from any of the Grid demo samples, I also consulted the documentation.
But still not clear on how to do it.

Do I need to subscibe to the change event?
.Events(events => events.Change("GSSelectionChange")

Or can I directly get the selected row and its DataItem like the following
var grid = $("#usersGrid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());

So far, getting the selected row and its DataItem directly (w/out subscribing to the Change event) doesn't work.

I would appreciate any help or tip on how to get this done.














4 Answers, 1 is accepted

Sort by
0
Dimiter Madjarov
Telerik team
answered on 10 Mar 2014, 03:59 PM
Hi Indy,


The change event of the Grid is fired when the selection has changed. I don't know if handling this is required in the current scenario.

Besides of that, you could retrieve the selected row and it's dataItem exactly as you specified in your post.
var grid = $("#usersGrid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());

This code snippet assumes that the current Grid is using an Ajax dataSource, row selection type (not cell) and that there is actually a selected row at the moment of executing it.

Please let me know if this information was helpful or I could assist you further.

Regards,
Dimiter Madjarov
Telerik
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
Sampath
Top achievements
Rank 1
commented on 31 Oct 2014, 06:20 AM

hi, I have a kendo UI grid in which I am using an entity framework data source to bind the data. I have enabled the multi select option in the grid. Now I want to pass the selected row ID's to the server side function for processing. How can I do this?

I am new to Kendo UI and MVC developments. I didn't come across proper documentation which does this for server bound Kendo grids.

Here is my grid, in index.cshtml

@model IEnumerable<CPMS.Models.CPMS_Daily>
@{
    ViewBag.Title = "Proactive Measures for Critical Events";
}

<h2>Proactive Measures for Critical Events</h2>
@(Html.Kendo().Grid(Model)
      .Name("Grid")
      .Columns(columns =>
          {
              columns.Command(command => { command.Edit(); command.Destroy().Text("Complete"); }).Width(100);
              columns.Bound(pro => pro.Schedule_Number__Color).Title("Schedule::Color");
              columns.Bound(pro => pro.CO_Number).Title("CO Number");
              columns.Bound(pro => pro.Plant).Title("Plant").Width(50);
              columns.Bound(pro => pro.Planning_Board).Title("Planning Board");
              columns.Bound(pro => pro.Style__Color).Title("Style::Color");
              columns.Bound(pro => pro.Event).Title("Event");
              columns.Bound(pro => pro.VTM_event).Title("VTM").Width(50);
              columns.Bound(pro => pro.Retain_target_date).Title("Retain TargetDate").Format("{0:dd/MM/yyyy}");
              columns.Bound(pro => pro.Current_target_date).Title("Current TargetDate").Format("{0:dd/MM/yyyy}");
              columns.Bound(pro => pro.Event_Responsible).Visible(false);
              columns.Bound(pro => pro.Event_notes).Title("Note").Width(200);
              columns.Bound(pro => pro.Order_Quantity).Title("Order Quantity");
              columns.Bound(pro => pro.Expected_Date).Title("Expected Date").Format("{0:dd/MM/yyyy}").EditorTemplateName("Date");
              columns.Bound(pro => pro.Days_Late).Title("Days Late").Width(20);
              columns.Bound(pro => pro.PackageExecutedDate).Visible(false);

          })
      .Pageable()
      .Sortable()
      .Filterable()
      .Scrollable(scr => scr.Height(500))
      .Groupable()
      .Selectable(s => s.Mode(GridSelectionMode.Multiple))
      .Editable(editable => editable.Mode(GridEditMode.InLine).DisplayDeleteConfirmation(false))
      .DataSource(dataSource => dataSource
        .Server()
        .PageSize(20)
            .Model(model =>
            {
                model.Id(r => r.RowID);
                model.Field(f => f.Schedule_Number__Color).Editable(false);
                model.Field(f => f.CO_Number).Editable(false);
                model.Field(f => f.Plant).Editable(false);
                model.Field(f => f.Planning_Board).Editable(false);
                model.Field(f => f.Style__Color).Editable(false);
                model.Field(f => f.Event).Editable(false);
                model.Field(f => f.VTM_event).Editable(false);
                model.Field(f => f.Retain_target_date).Editable(false);
                model.Field(f => f.Current_target_date).Editable(false);
                model.Field(f => f.Order_Quantity).Editable(false);
                model.Field(f => f.Days_Late).Editable(false);
                model.Field(f => f.Event_Responsible).Editable(false);
            }
            )
            .Read(read => read.Action("Index", "ProactiveKendo"))
            .Update(update => update.Action("Update", "ProactiveKendo"))
            .Destroy(destroy => destroy.Action("Destroy", "ProactiveKendo"))
    )
)

<script type="text/javascript">

    function Save() {
        var gridData = $("#Grid").data("kendoGrid").dataSource.data();;
        $.ajax({
            type: "POST"
            , url: "/ProactiveKendo/SaveGridData"
            , data: JSON.stringify({ model: gridData })
            , contentType: "application/json"
            , success: function (result) {
                alert(result.count + " record(s) found");
            }
        });

    }

</script>

<input type="button" onclick="Save()" value="Post Grid Data" />

And here is the code in my controller -(ProactiveKendoController)

using CPMS.Models;
using Kendo.Mvc.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace CPMS.Controllers
{
    public class ProactiveKendoController : Controller
    {
        //private CPMSEntities db = new CPMSEntities();
        private Entities db = new Entities();

        // GET: /ProactiveKendo/
        public ActionResult Index()
        {
            try
            {
                return View(db.CPMS_Daily.Where(e => e.Days_Late >= 0 && e.Event_Responsible == "SANJAYAS"));
            }
            catch (Exception ex)
            {
                return View("Error");
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update([Bind(Include = "RowID,Schedule_Number__Color,CO_Number,Plant,Planning_Board,Style__Color,Schedule_Number,Event,VTM_event,Retain_target_date,Current_target_date,Event_Responsible,Event_notes,Order_Quantity,Expected_Date,Days_Late,PackageExecutedDate")]CPMS_Daily cpmsdaily)
        {
            if (ModelState.IsValid)
            {
                CPMS_Daily rowId = db.CPMS_Daily.Single(r => r.RowID == cpmsdaily.RowID);
                rowId.Event_notes = cpmsdaily.Event_notes;
                rowId.Expected_Date = cpmsdaily.Expected_Date;
                db.SaveChanges();

                RouteValueDictionary routeValues = this.GridRouteValues();
                return RedirectToAction("Index", routeValues);
            }

            return View(db.CPMS_Daily.Where(e => e.Days_Late >= 0 && e.Event_Responsible == "SANJAYAS"));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Destroy(CPMS_Daily cpmsdaily)
        {
            if (ModelState.IsValid)
            {
                CPMS_Daily rowId = db.CPMS_Daily.Single(r => r.RowID == cpmsdaily.RowID);
                rowId.Event_Status = true;
                db.SaveChanges();

                RouteValueDictionary routeValues = this.GridRouteValues();
                return RedirectToAction("Index", routeValues);
            }

            return View(db.CPMS_Daily.Where(e => e.Days_Late >= 0 && e.Event_Responsible == "SANJAYAS"));
        }

        public ActionResult SaveGridData()
        {
            return View();
        }
        [HttpPost]
        public JsonResult SaveGridData(List<CPMS_Daily> users)
        {
            // Here i am not implementing all
            // I am interested to show controller is getting data from view
            var count = 0;
            if (users != null)
            {
                count = users.Count;
            }
            //Returns how many records was posted
            return Json(new { count = count });
        }
    }
}

When i run this code I'm getting 0 records found. Please help. Any assistance is much appreciated. :)
Dimiter Madjarov
Telerik team
commented on 31 Oct 2014, 11:15 AM

Hi Sampath,


The current Grid is using a server dataSource. In this case no data is stored on the client side, so the following expression won't work
var gridData = $("#Grid").data("kendoGrid").dataSource.data();

If retrieving the data is required, you should switch to Ajax dataSource instead.

Regards,
Dimiter Madjarov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Ronan
Top achievements
Rank 1
commented on 17 Jul 2015, 10:43 AM

This option don't work if you using  ClientTemplate  and html button like:

"<input type='button' class='k-button k-grid-btn-order-details' onclick='OrderDetail'  name 'order'  value='Order' />​"

 Is there other way to get the selected row DataItem? 

Dimiter Madjarov
Telerik team
commented on 17 Jul 2015, 12:08 PM

Hello Ronan,

It is not clear what issue are you experiencing with the current approach. Please elaborate further and demonstrate the problem.

Regards,
Dimiter Madjarov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Hari
Top achievements
Rank 1
answered on 13 Aug 2015, 03:07 PM

 Its simple

//Add this line of code to the grid
columns.Command(command => command.Custom("Remove").Click("removeItem"));
//Java script function to remove
       function removeItem(e) {
        //Get the instance of the grid
        var grid = $("#grid").data("kendoGrid");
        //Get the selected grid
        var tr = $(e.target).closest("tr");
        //Get the item from the grid
        var data = this.dataItem(tr);
        //Remove the item from the datasource
        grid.dataSource.remove(data);
        //Sync it with the grid
        dataSource.sync();
   }

0
Tom
Top achievements
Rank 1
answered on 16 Nov 2017, 09:22 AM

I personally think this is better than any solution I have seen across the internet.

var grid = $('#Grid').data('kendoGrid');
var selectedRow = grid.dataItem('tr.k-grid-edit-row');

selectedRow.FieldName

Stefan
Telerik team
commented on 20 Nov 2017, 06:39 AM

Hello, Tom,

Thank you for sharing the solution with the community.

Based on the code, I can assume that this approach can be used to retrieve the dataItem of the edited item instead of the selected one.

Also, the dataItem of the edited row can be easily retrieved on the edit event of the Grid:

https://docs.telerik.com/kendo-ui/api/javascript/ui/grid#events-edit

Regards,
Stefan
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Noah
Top achievements
Rank 1
answered on 14 Aug 2019, 01:45 PM
How would I go about this if I wanted to select a whole row as stated above, but instead of sending all of the rows content I would only send content from one of the columns?
Tsvetomir
Telerik team
commented on 16 Aug 2019, 06:47 AM

Hi Noah,

The approach that you refer to is the one which calls the sync() method of the data source, is that correct? This method actually would make a request to the remote service with the contents of the modified rows only. Therefore, it would like to send only the contents of one column, then, you would have to create a custom $.ajax() request. 

An example of how to get the dirty models would be:

var data = $("#grid").getKendoGrid().dataSource.data();
 
var dirty = $.grep($($0).getKendoGrid().dataSource.data(), function(item) {
    return item.dirty
});

Now "dirty" would be a collection with the modified models only. Within its properties there is one called "dirtyFields". It is an object which contains only the modified fields. 

After retrieving the dirty fields, you can initiate a custom ajax request and send the modified fields. It is important to point out that you would have to send the ID of the item as well.

Another option, actually, is to configure the update transport function of the grid to be a custom one. More information could be found in the article below. And more specifically under the "Specify update as a function" example:

https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.update

Let me know in case further assistance is required.


Best regards,
Tsvetomir
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Tags
Grid
Asked by
Indy
Top achievements
Rank 1
Answers by
Dimiter Madjarov
Telerik team
Hari
Top achievements
Rank 1
Tom
Top achievements
Rank 1
Noah
Top achievements
Rank 1
Share this question
or