Get PK of Selected Row Kendo Grid From Toolbar Button - kendo-ui

I have a Selectable Kendo Grid with a Custom Toolbar Button.
How can I get the selected row PK when button is Clicked?
I tried many tips but no one was working because I have a Server DataSource.
<%: Html.Kendo().Grid<Web.Models.Model>()
.Name("Grid")
.BindTo((IEnumerable<Web.Models.Model>)ViewBag.List)
.Columns(columns =>
{
columns.Bound(p => p.PK).Title("PK");
columns.Bound(p => p.STATUS).Title("Status");
columns.Bound(p => p.NOTES).Title("Notes");
})
.ToolBar(toolbar =>
{
toolbar.Custom();
toolbar.Template("<a class='k-button k-button-icontext' onClick='EditItem();' ></span>Edit Item</a>");
})
.DataSource(dataSource => dataSource
.Server()
.Model(Model => Model.Id(p => p.PK))
)
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Multiple))
%>
function EditItem(e) {
???
};

Please try with the below code snippet.
<script>
function EditItem() {
var grid = $("#Grid").data("kendoGrid");
var rows = grid.select();
rows.each(function (index, row) {
var selectedItem = grid.dataItem(row);
alert(selectedItem.PK);
});
}
</script>
Let me know if any concern.

hi you can use plain jquery for that as an another option
var rowID = $("#Grid .k-state-selected").find("td:eq(0)")[0].innerText
alert(rowID)

This one works!
function EditItem(e) {
var selectedRows = $("#Grid").find(".k-state-selected");
for (var i = 0; i < selectedRows.length; i++) {
var selectedRow = selectedRows[i];
var PK = selectedRows[i].cells[0].innerText;
}
};

Related

Pass the telerik grid column values to controller action result

I have to pass the Id and Date value to action result(Update) in a Index controller. But I am not able to pass the parameters by using below code:
#(Html.Telerik().Grid(Model)
.Name("NotesDetails")
.DataBinding(dataBinding => dataBinding.Ajax().Select("ListAjax", "NotesDetails"))
.Columns(columns =>
{
columns.Bound(o => o.Flag).Visible(false).Title("Flag");
columns.Bound(o => o.Id).Visible(false).Title("Id");
columns.Command(commands =>
{
commands.Custom("Flag value")
.Text("<img id='flag' width='20' height='10' src = '/Content/images/Flag.png' >")
.Ajax(true)
.Action("Update", "Index", new { id=#-Id#, date = #-Date# });
}).Title("Flag");
columns.Bound(o => o.Date).Visible(true).Title("Date");
columns.Bound(o => o.Author).Visible(true);
columns.Bound(o => o.Task).Visible(true);
})
.Pageable(pager =>
{
pager.Style(GridPagerStyles.PageSizeDropDown | GridPagerStyles.NextPrevious);
pager.Position(GridPagerPosition.Both);
pager.PageSize(50, new int[] { 50, 100, 500 });
})
If I give the values like .Action("Update", "Index", new { id=123, date = "2000/2/2"}); I am getting result
Thanks in advance
We handle this in a Jquery way
command.Custom("Update").Click("jQueryFilename.functionName").Text("Refresh User")
and in jQuery:
jQueryFilename.functionName = function(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var json = JSON.stringify(dataItem);
$.ajax({
url: Controllername/Index,
type: 'POST',
contentType: "application/json",
data: json
}).done(function () {
var grid = $("#Grid").data("kendoGrid");
grid.dataSource.read();
grid.refresh();
}
);
}
You'll need to get set the jQuery selector to get your id and and date but that's pretty straight forward.
Happy coding!

Get selected row on right mouse click in Kendo Grid

I have a Kendo Grid and I want to detect the right click and left click, so based on these I do two separate things. I used to get ID from the grid on either left or right click before and was working fine. But to fix an IE11 clicking problem I had to update the kendo.js to 2013.2.716 version and after that it detects left/right click all right but for "Right Click" can't get the selected row Id. The following is my code to detect left/right click and PlodId is a column in my grid:
function LoadMainShiftGrid() {
//For Right Click --> Delete Selected Shift
$("#shiftReport").delegate("tbody>tr", "contextmenu", function (e) {
if (e.which == 3) {
$("#plodDetails").hide();
var gridData = $('#shiftReport').data("kendoGrid");
var selectedRowData = gridData.dataItem($('.k-grid').find("tr.k-state-selected"));
// MY PROBLEM FOR RIGHT CLICK SELECTEDROWDATA COMES TO NULL <<<<
var SelectedPlodId = selectedRowData.PlodId;
}
});
//For Left Click --> Show Plod Detials
$("#shiftReport").delegate("tbody>tr", "click", function (e) {
if (e.which == 1) {
var gridData = $('#shiftReport').data("kendoGrid");
var selectedRowData = gridData.dataItem($('.k-grid').find("tr.k-state-selected"));
var SelectedPlodId = selectedRowData.PlodId;
}
});
}
Thank you in advance.
I've changed the click binding function to 'mousedown' and select the row manually (Thank you #drw85 for the idea) and after that it works fine.
function LoadMainShiftGrid() {
$('#shiftReport').data('kendoGrid').tbody.on('mousedown', function (e) {
//select the clicked row manually; this resolves all problem :D
$('#shiftReport').data("kendoGrid").select(e.target.parentElement);
if (e.which == 3) {
$("#plodDetails").hide();
var gridData = $('#shiftReport').data("kendoGrid");
var selectedRowData = gridData.dataItem($('.k-grid').find("tr.k-state-selected"));
var SelectedPlodId = selectedRowData.PlodId;
}
//For Left Click --> Show Plod Details
if (e.which == 1) {
var gridData = $('#shiftReport').data("kendoGrid");
var selectedRowData = gridData.dataItem($('.k-grid').find("tr.k-state-selected"));
var SelectedPlodId = selectedRowData.PlodId;
}
});
}
I think that happens, because the right click doesn't actually select the row.
You can select it through code, before you try to get it via
var selectedRowData = gridData.dataItem($('.k-grid').find("tr.k-state-selected"));
You should be able to get the click target through the event object and set the selected property on it via kendo.
var index = gridData.find(e.delegateTarget).index();
var dataItem = gridData.dataSource.view()[index];
dataItem.selected();
You might have to pass true to the selected function.
You can also get the selected row like this..
$("#shiftReport").on("mousedown", "tr[role='row']", function (e) {
if (e.which === 3) {
$(this).addClass("k-state-selected");
var gview= $('#shiftReport').data("kendoGrid");
var selectedRow = gview.dataItem($(this));
}
});
Use .Selectable() will high light the row when you hover over rows and click on any particular row, sample code:
#(Html.Kendo().Grid(Model)
.Name("Grid")
.DataSource(datasource => datasource
.Ajax()
.ServerOperation(false)
.PageSize(15)
)
.Sortable()
.Columns(columns =>
{
columns.Bound(model => model.NetworkID);
columns.Bound(model => model.FirstName);
columns.Bound(model => model.LastName);
})
.Filterable()
.Scrollable(s => s.Height(550))
.Pageable()
.Resizable(resize => resize.Columns(true))
.Selectable()
)
In IE 11 this will work
$("#grid").kendoGrid({
change: function(e) {
var selected = this.select();
var selectedDataItems = [];
for (var i = 0; i < selected.length; i++) {
var dataItem = this.dataItem($(selected[i]).closest("tr"));
selectedDataItems.push(dataItem);
}
}
});

How to use local html5 storage to save grid preferences in Kendo Grid

My grid is:
#(Html.Kendo().Grid<Stuff>()
.Name("Grid")
.DataSource(source => source.Ajax().Events(events=>events.Error("onError"))
.Events(events=>events.RequestEnd("onRequestEnd"))
.Model(model =>
{
model.Field(p => p.PurchaseQuantity).Editable(false);
model.Field(p => p.PurchasePrice).Editable(false);
})
.Read("GetData", "Data"))
.Columns(columns =>
{
columns.Bound(o => o.PurchaseQuantity).Width(100);
columns.Bound(o => o.PurchasePrice).Format("{0:C}").Width(100);
})
.Sortable()
.Pageable(page=> page.PageSizes(new int[] { 10, 20, 50, 100 }).Refresh(true))
.Filterable(filterable => filterable.Extra(false))
.Events(boo=>boo.DataBound("onTest"))
.HtmlAttributes(new { style = "width:850px" })
)
and the javascript used to load data is:
<script type="text/javascript">
var storage = window.localStorage;
var storageLoaded = false;
function onError() {
$("#Grid").data("kendoGrid").dataSource.cancelChanges();
}
function onTest() {
if (!storageLoaded) {
console.log('loading size from storage ' + storage.pageSize);
storageLoaded = true;
console.log('marked storage loaded');
$("#Grid").data("kendoGrid").dataSource.pageSize(storage.PageSize);
console.log('set pagesize from storage ' + storage.pageSize);
var pagesize = $("#Grid").data("kendoGrid").dataSource.pageSize();
console.log('page size is ' + pagesize);
}
}
function onRequestEnd(e) {
if (storageLoaded) {
var pagesize = $("#Grid").data("kendoGrid").dataSource.pageSize();
storage.pageSize = pagesize;
console.log('setting size to storage ' + storage.pageSize);
}
}
firebug console shows:
loading size from storage 50 / marked storage loaded / set pagesize from storage 50 / page size is 10
Questions:
Why does the pagesize not save after set?
Is there a better way to accomplish this?
Is there a way to attach to the pagesize selector instead of using requestEnd?
Found a solution. Make the grid .AutoBind(false)
then
$(document).ready(function () {
storageLoaded = true;
$("#Grid").data("kendoGrid").dataSource._pageSize = storage.pageSize;
$("#Grid").data("kendoGrid").dataSource.read();
});
now this is making use of an _ variable inside the datasource which could break at any point in the future, but for now it does work.
I removed the databound event completely, a friend at Telerik was most helpful in getting me to the solution.
Hoping that in the future there will be something like:
.Pageable(page=> page.PageSizes(true).Refresh(true).Sticky("gridPageSizeDefault")
which will store the value in html5 local storage using the gridPageSizeDefaultkey.

kendo ui grid row how to set background color?

I need to change the row color of a kendo ui grid depending on a particular condition. I am using server side bindings with MVC. My code is as follows,
var grid = Html.Kendo().Grid<AllocateCOESGridViewModel>();
grid.Name("AllocateResultGrid")
.RowAction(row =>
{
if (row.DataItem.COESNo == 13054915)
{
row.HtmlAttributes["style"] = "background:blue";
}
else
{
row.HtmlAttributes["style"] = "background:red";
}
})
.Columns(columns =>
{
columns.Bound(s => s.COESNo).Title(#Allocate.COESGridHeading);
columns.Bound(s => s.Street).Title(#Allocate.StreetGridHeading);
columns.Bound(s => s.Suburb).Title(#Allocate.SuburbGridHeading);
columns.Bound(s => s.Postcode).Title(#Allocate.PostcodeGridHeading);
columns.Bound(s => s.InspectorName).Title(#Allocate.InspectorGridHeading);
columns.Bound(s => s.COESNo).Title(#Allocate.AllocateGridHeading + "<input type ='checkbox' id ='SelectAll' />").ClientTemplate("<input type ='checkbox' data-id='#= COESNo #' class='allocate' />").Sortable(false);
});
The grid works but no row colors at all? no blue or red.. I just get the standard white and grey.. any thoughts?
Thanks
This is how I got this to work, just wondering if there is any other options, as looping through the grid seems like a not so good idea... especially if the grid is long
var grid = $("#AllocateResultGrid").data("kendoGrid");
grid.bind("dataBound", updateGridRows);
updateGridRows: function()
{
dataView = this.dataSource.view();
for (var i = 0; i < dataView.length; i++)
{
if (dataView[i].Selected == false)
{
var uid = dataView[i].uid;
$("#AllocateResultGrid tbody").find("tr[data-uid=" + uid + "]").addClass("customClass");
}
}
}
I added the customClass in my stylesheet
I had the same issue, let me know if you find one without loops!
var grid = $("#AllocateResultGrid").data("kendoGrid");
var data = grid.dataSource.data();
$.each(data, function (i, row) {
if (row.Selected == false)
$('tr[data-uid="' + row.uid + '"] ').addClass("customClass");
}

MVC Kendo UI Grid = Custom Button can't return selected row id

I want to get the selected row "ID" but it just failed... and i have totally no clue what is happening here.
MVC HTML Code :
#(Html.Kendo().Grid(Model)
.Name("grid")
.HtmlAttributes(new { style = "margin-top: 5px" })
.Columns(c =>
{
c.Bound(model => model.mgID);
c.Command(com => { com.Custom("Edit").Click("Edit");});
})
.Pageable()
.Sortable()
.Selectable()
.DataSource(d => d
.Ajax()
.PageSize(20)
.Model(model => model.Id(i => i.mgID))
.Read(r => r.Action("Manage_Read", "Manage"))
.Destroy(o => o.Action("Manage_Destroy", "Manage"))
)
)
Javascript Code :
function Edit() {
var grid = $("#grid").data("kendoGrid");
var row = grid.select();
var selectedRowIndex = row.index(); //Return "-1"
var dataItem = grid.dataItem(row); //Return "Undefined"
}
Please tell me, what am i miss out??
If all you need is get the dataItem of the row containing the clicked "Edit" button, you can use:
function Edit(e) {
var dataItem = this.dataItem($(e.target).closest("tr"));
}
NOTE:
in the context of click event this is the grid.
in that same context e.target is your button, so we look for the closest table row.

Resources