I have a Treeview. On selecting the edit of the treenode a kendo grid for Roles will be displayed and few textboxes (where is edit other properties for roles). The kendo grid for roles have checkboxes and Rolenames. My current code is working if I select one checkbox.
What I need is how I get the array of the ids of the roles if I check multiple checkboxes. Tried multiple ways but I am not getting the list of ids when multiple checkboxes are selected. On click edit of the node EditNode is triggered and on click of save the 'click' is trigerred.
Below is my code:
function editNode(itemid) {
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
.html(editTemplate({ node: node }))
.appendTo("body")
.kendoWindow({
title: "Node Details",
modal: true,
open: function () {
console.log('window opened..');
editDS = new kendo.data.DataSource({
schema: {
data: function (response) {
return JSON.parse(response.d); // ASMX services return JSON in the following format { "d": <result> }.
},
model: {// define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
Id: { editable: false, nullable: false, type: "string" },
name: { editable: true, nullable: true, type: "string" },
NodeId: { editable: false, nullable: false, type: "string" },
}
},
},
transport: {
read: {
url: "/Services/MenuServices.asmx/getroles",
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "POST", //use HTTP POST request as the default GET is not allowed for ASMX
datatype: "json",
},
}
});
rolesGrid = $("#kgrid").kendoGrid({
dataSource: editDS,
height: 150,
pageable: false,
sortable: true,
binding: true,
columns: [
{
field: "name",
title: "Rolename",
headerTemplate: '<span class="tbl-hdr">Rolename</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
{
template: kendo.template("<input type='checkbox' class = 'checkbox' id='chkbx' data-id='#:Id #' />"),
attributes: {
style: "vertical-align: top; text-align: center;"
}
},
],
}).data('KendoGrid');
},
})
.on("click", ".k-primary", function (e) {
var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
var textbox = dialog.element.find(".k-textbox");
var LinKLabel = $('#LL').val();
var roles = $(chkbx).data('roleid');
console.log(PageLocation);
node.text = undefined;
node.set("LINK_LABEL", LinKLabel);
node.set("Roles", roles);
dialog.close();
var treenode = treeview.dataSource.get(itemid);
treenode.set("LINK_LABEL", LinKLabel);
treenode.set("id", Id);
treenode.set("roles", roles);
treenode.LINK_LABEL = LinKLabel;
treenode.ID = Id;
treenode.roles = roles;
var rid = $(chkbx).data('roleid');
$.ajax({
url: "/Services/MenuServices.asmx/UpdateTreeDetails",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
data: JSON.stringify({ "Json": treenode })
});
console.log(JSON.stringify(treenode));
})
}
I'm assuming you want to get those ids in this line:
var roles = $(chkbx).data('roleid');
Right? What I don't know is the format you want to get that data. With the following code you can get the roles data in an array objects like this { id: 1, value: true }, check it out:
var grid = $("#grid").data("kendoGrid"),
ids = [];
$(grid.tbody).find('input.checkbox').each(function() {
ids.push({
id: $(this).data("id"),
value: $(this).is(":checked")
});
});
Demo. Anyway you want it, you can change it inside the each loop.
Update:
To get only the checked checkboxes, change the selector to this:
$(grid.tbody).find('input.checkbox:checked')
Demo
Related
I need to set Kendo grid action button Icon based on value. My code as follows,
function InitProductServicesGrid() {
var prodServiceDataSource = new kendo.data.DataSource({
transport: {
type: "json",
read:
{
url: SERVER_PATH + "/LTSService/ProductsService.asmx/GetProductServiceDetailsList",
type: "POST",
contentType: 'application/json',
data: GetAdditonalData,
datatype: "json"
},
update:
{
url: SERVER_PATH + "/LTSService/ProductsService.asmx/SaveProductService",
type: "POST",
contentType: 'application/json',
datatype: "json"
}
},
schema: {
data: function (result) {
return JSON.parse(result.d);
},
model: {
id: "Id",
fields: {
Id: { type: "int" },
ServiceTime: { type: "string" },
IsActive: { type: "boolean"}
}
}
},
requestEnd: function (e) {
if (e.type === "destroy") {
var grid = $("#productServicesGrid").data("kendoGrid");
grid.dataSource.read();
}
},
error: function (e) {
e.preventDefault();
if (e.xhr !== undefined && e.xhr !== null) {
var messageBody = e.xhr.responseJSON.Message;
ShowGritterMessage("Errors", messageBody, false, '../App_Themes/Default/LtsImages/errorMessageIcon_large.png');
var grid = $("#productServicesGrid").data("kendoGrid");
grid.cancelChanges();
}
},
pageSize: 20,
});
$("#productServicesGrid").kendoGrid({
dataSource: prodServiceDataSource,
sortable: true,
filterable: false,
pageable: true,
dataBound: gridDataBound,
editable: {
mode: "inline",
confirmation: false
},
columns: [
{ field: "Id", title: "", hidden: true },
{
field: "ServiceTime",
title: "Time Standard",
sortable: false,
editor: function (container, options) {
var serviceTimeTxtBox = RenderServiceTime();
$(serviceTimeTxtBox).appendTo(container);
},
headerTemplate: '<a class="k-link" href="#" title="Time Standard">Time Standard</a>'
},
{
title: "Action", command: [
{
name: "hideRow",
click: hideRow,
template: comandTemplate
}
],
width: "150px"
}
]
});
}
I wrote a custom template function as follows,
function comandTemplate(model) {
if (model.IsActive == true) {
return '<a title="Hide" class="k-grid-hideRow k-button"><span class="k-icon k-i-lock"></span></a><a title="Hide"></a>';
}
else {
return '<a title="Show" class="k-grid-hideRow k-button"><span class="k-icon k-i-unlock"></span></a><a title="Show"></a>';
}
}
But when I debug the I saw the following value for model value.
I followed this sample code as well. here you can see, I also set the custom template like the sample code. Please help me to solve this. Why I can't access model IsActive value from comandTemplate function.
Updated
When clicking hideRow action, I access the dataItem as follows.
function hideRow(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
if (dataItem.IsActive == true) {
dataItem.IsActive = false;
}
else {
dataItem.IsActive = true;
}
}
Is there any possible way to access data from template function as above or any other way?
I would suggest a different approach because you can't access grid data while rendering and populating grid.
My suggestion is to use two actions and hide it based on the flag (in your case IsActive).
Something like this: Custom command
NOTE: in visible function you can access item!
EDIT: you can access it and change it on dataBound traversing through all data.
Check this example: Data bound
I don't see the advantage of relying on the grid commands. You can render any button you want yourself and and use the dataBound event to bind a click handler:
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{
template: function(dataItem) {
const isActive = dataItem.isActive;
return `<a title=${isActive ? "Hide": "Show"} class="k-grid-hideRow k-button"><span class="k-icon k-i-${isActive ? 'lock' : 'unlock'}"></span></a>`
}
}
],
dataBound: function(e) {
e.sender.tbody.find(".k-grid-hideRow").click(evt => {
const row = evt.target.closest("tr")
const dataItem = e.sender.dataItem(row)
dataItem.set("isActive", !dataItem.isActive)
})
},
dataSource: [{ name: "Jane Doe", isActive: false }, { name: "Jane Doe", isActive: true }]
});
Runnable Dojo: https://dojo.telerik.com/#GaloisGirl/eTiyeCiJ
i am trying to do a server side processing which is load on demand , i am using mvc to develop my application
the following is my code on the datatables js class,
var initTrackingTable = function () {
var table = $('#tableCategoryList');
var daterange = $("#daterangepicker").val();
val_CategoryName = $("#SearchTextBox").val();
//val_Daterange = $("#trackingForm").find("[name='daterangepicker']").val();
settingsInitEmpty = {
ajax: ({
url: "/Product/LoadCategoryData?category=" + val_CategoryName,
type: "POST",
datatype: "json"
}),
// ### FOR SERVERSIDE LODING
processing: true,
serverSide: true,
filter: false,
orderMulti: false,
columns: [
{ data: "category_id", name: "category_id", autoWidth: true },
{ data: "category_name", name: "category_name", autoWidth: true, render: function (data, type, row) { return '<span class="">' + data + '</span>' } },
{ data: "sort_order", name: "sort_order", autoWidth: true },
],
initComplete: function (settings, json) {
$("#tableCategoryList").parent().addClass("tableTransactionGridWrapper")
}
};
categoryTable = table.DataTable(settingsInitEmpty);
}
on the category_name there, i wish to put the hyperlink, however the hyperlink i intend to put the category_id as a query string parameter so i am able to edit the category. may i ask is this achievable? if yes, how the code suppose to be?
I'm just getting to grips with Slickgrid (with an asp.net MVC back end) as a simple start I want to us it as an editing grid for a Key/Value pair of systems settings. I have it working OK for Add, but update works OK unless we edit the key.
Because we have changed the key value it always looks like a new Key/Value pair rather than modifying the existing item. So my question is, how do I let the backend know what item I am modifying ?
I figure I could add an extra field (holding the original id) to the dataview, but I am kind of wondering if I a missing some functionality that makes this easier.
$(function() {
var grid;
var columns = [{
id: "id",
name: "Name",
field: "id",
editor: Slick.Editors.Text
}, {
id: "Value",
name: "Value",
field: "Value",
editor: Slick.Editors.Text
}, ];
var options = {
enableColumnReorder: false,
editable: true,
enableAddRow: true,
enableCellNavigation: true,
autoEdit: false
};
var dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.onCellChange.subscribe(function(e, args) {
var row = dataView.getItem(args.row);
var value = row[grid.getColumns()[args.cell].field];
var id = row[grid.getColumns()[0].field];
var data = {
value: value,
id: id
};
var url = "#Url.Action("Update", "SystemSettings")";
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(a) {
if (a.status != "ok") {
alert(a.msg);
undo();
} else {
alert(a.msg);
}
return false;
}
});
});
grid.onAddNewRow.subscribe(function(e, args) {
var item = {
"id": dataView.length,
"value": "New value"
};
$.extend(item, args.item);
dataView.addItem(item);
});
dataView.onRowCountChanged.subscribe(function(e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function(e, args) {
grid.invalidateRows(args.rows);
grid.render();
});
$.getJSON('#Url.Action("GetAll", "SystemSettings")', function(data) {
dataView.beginUpdate();
dataView.setItems(data);
dataView.endUpdate();
});
});
My requirement is for a grid that allows users to be able to perform all the basic CRUD functions on a database table. So am I going in the right direction with this or should I be doing something different.
So, I guess I hadn't quite grasped how the data view is disconnected from the grid. So I decided to store the key field twice in there once as a (non editable) Id field and once as an editable name field.
Once I realised that I could detect the old & new versions of the key field:
$(function () {
var grid;
var columns = [
{ id: "name", name: "Name", field: "name", editor: Slick.Editors.Text },
{ id: "value", name: "Value", field: "value", editor: Slick.Editors.Text },
];
var options = {
enableColumnReorder: false,
editable: true,
enableAddRow: true,
enableCellNavigation: true,
autoEdit: false
};
var dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.onCellChange.subscribe(function (e, args) {
var row = dataView.getItem(args.row);
var id = row["id"];
var value = row["value"];
var name = row["name"];
var data = { value: value, id: id, name: name };
var url = "#Url.Action("Update", "SystemSettings")";
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function (a) {
if (a.status != "ok") {
alert(a.msg);
undo();
} else {
alert(a.msg);
}
return false;
}
});
});
grid.onAddNewRow.subscribe(function (e, args) {
var item = { "id": args["name"], "value": "New value" };
$.extend(item, args.item);
dataView.addItem(item);
});
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
grid.render();
});
$.getJSON('#Url.Action("GetAll", "SystemSettings")', function (data) {
dataView.beginUpdate();
dataView.setItems(data);
dataView.endUpdate();
});
});
For some reasons I cannot use MVC-wrapper of Kendo grid. So I am trying to build Kendo grid on JavaScript.
There are 2 main problems when trying to update or create records on grid.
1-)All operations(destroy,update,create) on grid just go to create action by Datasource's of Kendo grid. For example after update a record, datasource send data to this URL to many times(number of columns):
http://localhost:63186/Administrator/DefinitionDetailCreate. It should pass values to:
http://localhost:63186/Administrator/DefinitionDetailUpdate
2-)After operation(update or create) Grid sends all data to Action Method instead of new or updated data. So it sends requests the number of columns on grid
JavaScript:
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
data: {DefinitionCode: code},
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")',
type: "POST",
dataType: "text"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "text",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "text",
}
},
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: {editable: false, nullable: true},
DESCRIPTION: {validation: {required: true}}
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: {style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{command: ["edit", "destroy"], title: "Operasyon", width: "100px"}],
editable: "popup"
});
Controller:
[HttpPost]
public ActionResult DefinitionDetailUpdate(Guid ID,Guid REFERENCEID,string DESCRIPTION)
{
return null;
}
[HttpPost]
public ActionResult DefinitionDetailCreate(Guid ID, Guid REFERENCEID, string DESCRIPTION)
{
return null;
}
First you might need to add parameterMap, this will help identify server side methods:
parameterMap: function (options, operation) {
var out = null;
switch (operation) {
case "create":
out = '{ "param":' + options.somevalue + '}';
break;
case "read":
out = '{ "id":' + options.somevalue + '}';
break;
case "update":
out = '{ "id":' + options.somevalue + '}';
break;
case "destroy":
out = '{ "id": ' + options.somevalue + '}';
break;
}
return out;
}
I would also suggest to keep all the dataTypes as dataType: "json"
Also you seem to be missing contentType in your transports definitions :
update: {
url: _op.serviceBaseUrl + "Update",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
complete: function (jqXhr, textStatus) {
}
},
i have posted answer for the same type of question, you may have a check
or
you may Use this code
js
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
type: "POST",
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")' ,
type: "POST",
dataType: "json"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "json",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "json",
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
} },
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: { editable: false, nullable: true },
DESCRIPTION: { validation: { required: true } }
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: { style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{ command: ["edit", "destroy"], title: "Operasyon", width: "100px" }],
editable: "popup"
});
Controller
[HttpPost]
public ActionResult DefinitionDetailUpdate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
[HttpPost]
public ActionResult DefinitionDetailCreate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
Note that parameterMap: function() send updated data in serialize string format with name models so you should use "models" as parameter name in your action
i hope this will help you:)
I am trying to "filter" a grid based on an option selected from a select drop down.
How do I send the selected option value to the grid when the change event on the select dropdown fires?
My grid datasource is:
dataSourceParts = new kendo.data.DataSource({
serverPaging: false,
serverFiltering: false,
serverSorting: false,
transport: {
read: {
url: ROOT + 'shipment/partsSerialGrid',
dataType: 'json',
type: 'POST',
data: {
enquiryId: enquiryId
}
}
},
pageSize: 25,
error: function(e) {
alert(e.errorThrown + "\n" + e.status + "\n" + e.xhr.responseText);
},
schema: {
data: "data",
total: "rowcount",
model: {
id: 'id',
fields: {
quantity: {
type: 'number',
editable: false
},
idealForm: {
type: 'string',
editable: false
},
serial: {
type: 'string',
editable: true
}
}
}
}
})
My select event:
$('#fromNameSelect').change(function() {
var fromMode = $('#fromSelect').val();
if (fromMode == 2)
{
supplierId = $(this).val();
dataSourceParts.filter({
field: 'test', operator: 'eq', value: 'test' // THIS DOES NOTHING.
});
$('#shippingPartsGrid').data('kendoGrid').dataSource.read();
}
})
I cant confirm this. But since you set filter in dataSourceParts. Shouldn't you be using dataSourceParts.read() instead of $('#shippingPartsGrid').data('kendoGrid').dataSource.read();?
$('#fromNameSelect').change(function() {
var fromMode = $('#fromSelect').val();
if (fromMode == 2)
{
supplierId = $(this).val();
$('#shippingPartsGrid').data('kendoGrid').dataSource.filter({
field: 'test', operator: 'eq', value: 'test' // DO IT LIKE THIS
});
}
})