I have a selectable kendoUI grid in my ASP.NET MVC app. How do I get the strongly typed model object for the selected item? I have tried the following code but it doesn't work.
@(Html.Kendo().Grid<Backup>(Model.Backups)
.Name("MatchingBackupsGrid")
.Columns(col =>
{
col.Bound(backup => backup.BackupUId).Title("UID");
col.Bound(backup => backup.BackupFirstName).Title("First Name");
col.Bound(backup => backup.BackupLastName).Title("Last Name");
})
.Scrollable()
.Selectable(sel =>
{
sel.Mode(GridSelectionMode.Single);
sel.Type(GridSelectionType.Row);
})
.DataSource(dataSource => dataSource
.Server()
.Read(read => read.Action("SearchForBackup", "Arr", new { lastName = Model.SearchTerm }))
.Model(model => model.Id(backup => backup.BackupUId))
)
)
function SelectBackupButtonClickHandler() {
var grid = $("#MatchingBackupsGrid").data("kendoGrid");
var selectedBackup = grid.dataItem(grid.select());
console.log(selectedBackup);
}
I have no idea what it was that I was doing earlier, my code is working now.
I tried so many things -- I assumed for some reason that
grid.select()
returns an array, so I tried to apply an indexer to get the first element of the array like so:I also tried a transformation on the array like so:
I was in between so many ideas I was trying that I forgot to check that my original code did actually have a strongly typed model of the selected row.
So, just for the record, the code in the question is correct, and it is reproduced below. To get the selected item in a single selection mode KendoUI grid, do the following:
Grid row selection responds to the Kendo
change
event.With kendoHelpers you can get the selected item's dataItem
The other method which is
getSelectedDataItemByCurrentCell
doesn't require the grid to be selectable and works on the active cell.The library also has many other helper functions.
When you're using client-side code, you can only access client-side data; you can't access the strongly typed model using
grid.dataItem()
. If you want to do that, you'll need to send the item's id to the server, e.g. using an AJAX request, and continue your work there; so you'll have to do something like this: