Paging numbers are not displayed in a Kendo Grid - kendo-ui

When I refresh the page using filterOCPPLogRefresh() function, paging numbers are not displayed.
getOCCPLog.js:
Vestel.EVCMS.OCPPLogs.GetOCPPLogs = function (chargePointID) {
$(".k-loading-image").show();
$(document).ready(function () {
// OCPP Log Grid
filterStart = $("#start").data("kendoDateTimePicker").value();
filterEnd = $("#end").data("kendoDateTimePicker").value();
messageType = $("#dropdowntree").data("kendoDropDownTree").value();
var direction = "AllMessageDirection";
var wnd, detailsTemplate;
var messageDirection = {
'ReceivedAtGateway': Vestel.EVCMS.Common.OCPPLogsColumns.Outgoing,
'SentByGateway': Vestel.EVCMS.Common.OCPPLogsColumns.Incoming
};
$("#OCPPLogGrid").kendoGrid({
dataSource: {
transport: {
read: {
url:
Vestel.EVCMS.Common.Global.EVCApiUrl +
"api/ChargePoint/GetOCPPLogs?ChargePointID=" + chargePointID +
"&filterStart=" + filterStart.toDateString() +
" &filterEnd=" + filterEnd.toDateString() +
"&messageType=" + messageType +
"&direction=" + direction,
headers: {
"accept": "application/json;odata=verbose",
'Authorization': 'Bearer ' + Vestel.EVCMS.Common.Global.accessToken,
},
dataType: "json"
}
},
schema: {
model: {
id: "id",
fields: {
messageDate: {
type: "date",
editable: false,
},
messageID: {
editable: false,
},
messageDirection: {
editable: false,
},
messageType: {
editable: false,
},
messageDetails: {
type: "dynamic",
editable: false,
}
}
},
}
},
pageable: {
pageSize: 20,
pageSizes: [10, 20, 30, 40, 50]
},
scrollable: true,
persistSelection: true,
resizable: true,
sortable: true,
columnMenu: true,
toolbar: kendo.template($("#ocpplogtemplate").html()),
columns: [
{ selectable: true, width: "50px" },
{
field: "messageDate",
format: "{0:dd.MM.yyyy HH.mm.ss.fff}",
title: Vestel.EVCMS.Common.OCPPLogsColumns.MessageDate
},
{
field: "messageID",
title: Vestel.EVCMS.Common.OCPPLogsColumns.MessageID
},
{
field: "messageDirection",
title: Vestel.EVCMS.Common.OCPPLogsColumns.MessageDirection,
template: function (dataItem) {
return messageDirection[kendo.htmlEncode(dataItem.messageDirection)]
}
},
{
field: "messageType",
title: Vestel.EVCMS.Common.OCPPLogsColumns.MessageType
},
//{ field: "messageDetails", title: Vestel.EVCMS.Common.OCPPLogsColumns.MessageDetails, width: 550 },
{
command: {
text: Vestel.EVCMS.Common.OCPPLogsColumns.MessageDetails,
click: showDetails
},
width: "200px"
}
],
editable: "popup"
});
wnd = $("#loggrid")
.kendoWindow({
title: Vestel.EVCMS.Common.OCPPLogsColumns.CustomDimensionsRaw,
modal: true,
visible: false,
resizable: false,
scrollable: true,
draggable: true,
width: '700px',
height: '200px'
}).data("kendoWindow");
detailsTemplate = kendo.template($("#template").html());
function showDetails(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
}
Here the read, create, update and destroy functions work well. But the paging is not working.
pageSize: 20 is working. Only 20 items are showing, but the footer part is not working. I can not change to next page, the buttons are not working and the footer showing no items available.
I searched and found some similar questions, but the answers didn't work for me.
Screenshot of grid showing the problem
filterOCPPLogRefresh() function:
function filterOCPPLogRefresh(e) {
filterStart = $("#start").data("kendoDateTimePicker").value();
filterEnd = $("#end").data("kendoDateTimePicker").value();
messageType = $("#dropdowntree").data("kendoDropDownTree").value();
chargePointID = $("#chargePointID").val();
direction = $("#messageDirection").data("kendoDropDownList").value();
$.ajax({
type: "GET",
url: Vestel.EVCMS.Common.Global.EVCApiUrl +
"api/ChargePoint/GetOCPPLogs?ChargePointID=" + chargePointID +
"&filterStart=" + filterStart.toDateString() +
" &filterEnd=" + filterEnd.toDateString() +
"&messageType=" + messageType +
"&direction=" + direction,
contentType: "application/json; charset=utf-8",
headers: {
"accept": "application/json;odata=verbose",
'Authorization': 'Bearer ' + Vestel.EVCMS.Common.Global.accessToken,
},
dataType: "json",
success: function (data) {
for (var i = 0; i < data.length; i++) {
if (data[i].messageDate) {
var messageDate;
var messageDateFormatted;
if (data[i].messageDate != null) {
messageDate = new Date(data[i].messageDate.toString());
messageDateFormatted =
("0" + messageDate.getDate()).slice(-2) + "." +
("0" + (messageDate.getMonth() + 1)).slice(-2) + "." +
messageDate.getFullYear() + " " +
("0" + messageDate.getHours()).slice(-2) + ":" +
("0" + messageDate.getMinutes()).slice(-2) + ":" +
("0" + messageDate.getSeconds()).slice(-2) + ":" +
("0" + messageDate.getMilliseconds()).slice(-3);
} else {
messageDateFormatted = " - ";
}
data[i].messageDate = messageDateFormatted;
}
}
$("#OCPPLogGrid").data("kendoGrid").setDataSource(data);
},
error: function (error, data) {
}
});
}

Related

KendoUI populate dropdown

I am new to kendoUI and I need some assistance with getting the data that is returned from a function to populate into the dropdown. I am currently getting [object HTMLSelectElement] - you can see in the image attached. Any help is appreciated.
data is returned in function
dropdown is not showing the years returned
LoadAcceptedSubmissionsGrid: function (module) {
// Grid for "Accepted" tab
var isAccepted = "true";
gridAcceptedSubmissions = $("#gridAcceptedSubmissions").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
serverSorting: true,
serverFiltering: true,
allowUnsort: true,
transport: {
read: function (options) {
var strFilter = JSON.stringify(options.data.filter);
var strSort = JSON.stringify(options.data.sort);
var pageSize = options.data.pageSize === undefined && gridAcceptedSubmissions !== null ?
gridAcceptedSubmissions.dataSource.total() :
options.data.pageSize;
var acceptedSubmissionsUrl = commonUrl + "/Forms/Submissions/"
+ upacsSessionId + "/" + userId + "/" + form + "/" + isAccepted + "/"
+ options.data.page + "/" + pageSize + "/" + options.data.skip;
$.ajax({
type: "POST",
url: acceptedSubmissionsUrl,
xhrFields: {
withCredentials: true
},
data: {
filter: strFilter,
sort: strSort
},
success: function (response) {
options.success(response);
},
error: function (result) {
options.error(result);
}
});
}
},
pageSize: 10,
batch: false,
schema: {
total: function (response) {
return response.total;
},
data: function (response) {
return response.values;
},
model: {
id: "submissionId",
fields: {
state: { editable: false, type: "string", sort: "asc" },
fipsCode: { editable: false, type: "number", sort: "asc" },
year: { editable: false, type: "number", sort: "desc" },
name: { editable: false, type: "string" },
createdBy: { editable: false, type: "string" },
createdOn: { editable: false, type: "date" },
lastModifiedBy: { editable: false, type: "string" },
lastModifiedOn: { editable: false, type: "date" },
isEditable: { editable: false, type: "boolean" },
isReviewable: { editable: false, type: "boolean" }
}
}
}
},
groupable: false,
sortable: {
showIndexes: true,
mode: "multiple"
},
resizable: true,
selectable: "row",
scrollable: true,
filterable: true,
navigatable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 10
},
dataBound: this.GridDataBound,
columns: [
{
field: "submissionId",
title: "Id",
},
{
field: "state",
title: "State",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("state", "name", true)
},
sort: "ascending"
},
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("year", null, true)
},
sort: "descending"
},
{
field: "status",
title: "Status",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("status", null, true)
}
},
{
field: "createdBy",
title: "Initiated By",
filterable: {
ui: this.FormCreatedByAcceptedFilter
}
},
{
field: "createdOn",
title: "Initiated On",
format: "{0:g}",
},
{
field: "lastModifiedBy",
title: "Modified By",
filterable: {
ui: this.FormLastModifiedByAcceptedFilter
}
},
{
field: "lastModifiedOn",
title: "Modified On",
format: "{0:g}"
},
{
title: "Action",
headerTemplate: "<div class='headerTemplate'><span class='headerText'>Action</span>" +
"<button class='clearAllFilters' id='clearAllFiltersAcceptedSubmissions' tabindex=0> Clear All Filters</button></div>",
command: [
{
name: "View",
text: " ",
visible: function (dataItem) { return !dataItem.isEditable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-View' title='View Form' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-eye'><span class='sr-only'>View form</span></i></a>";
return tmpl;
},
click: function (e) {
e.preventDefault();
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-existing-form", module);
}
},
{
name: "View History",
text: " ",
visible: function (dataItem) { return !dataItem.isReviewable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-ViewHistory' title='View Form History' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-history'><span class='sr-only'>View form history</span></i></a> ";
return tmpl;
},
click: function (e) {
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-status-history", module);
}
}
],
},
]
}).data("kendoGrid");
gridAcceptedSubmissions.hideColumn(0);
$("#clearAllFiltersAcceptedSubmissions").click(function () {
gridAcceptedSubmissions.dataSource.filter({});
});
},
Without seeing what BuildMultiCheckboxDataSource is doing, I can only make assumptions.
However, since you have declared year as an IEnumerable<int> then the datasource does not need to be anything elaborate. Simply set it to the collection being returned by the server:
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/my-endpoint-to-fetch-years-here"
}
}
})
},
sort: "descending"
}

KendoDropDownList clear value

I use kendoDropDownList and have the following code:
<div id="memberNotInit-grid"></div>
<script>
$(document).ready(function () {
$("#memberNotInit-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("MemberNotInitList", "RandomPoolInit"))",
type: "POST",
dataType: "json",
data: function() {
var data = {
};
addAntiForgeryToken(data);
return data;
}
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: #(Model.PageSize),
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
pageSizes: [#(Model.AvailablePageSizes)],
#await Html.PartialAsync("_GridPagerMessages")
},
editable: {
confirmation: "#T("Common.DeleteConfirmation")",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "FirstName",
title: "#T("PoolMemberList.Fields.FirstName")",
width: 150
},
{
field: "LastName",
title: "#T("PoolMemberList.Fields.LastName")",
width: 150
},
{
field: "Status",
template: columnTemplateFunction
},
{
field: "Reason",
width: 150,
template: "<input data-bind='value:Reason' class='reasonTemplate' />",
//hidden: true
}
],
dataBound: function (e) {
var grid = e.sender;
var items = e.sender.items();
items.each(function (e) {
var dataItem = grid.dataItem(this);
var ddt = $(this).find('.dropDownTemplate');
$(ddt).kendoDropDownList({
value: dataItem.value,
dataSource: ddlDataSource,
dataTextField: "displayValue",
dataValueField: "Status",
change: onDDLChange
});
var reason = $(this).find('.reasonTemplate');
$(reason).keydown(reasonChange);
reason.hide();
});
}
});
var ddlDataSource = [
{
Status: #((int)DriverRandomPoolStatus.Enrollment),
displayValue: "Enrollment"
},
{
Status: #((int)DriverRandomPoolStatus.Active),
displayValue: "Active"
},
{
Status: #((int)DriverRandomPoolStatus.Excused),
displayValue: "Excused"
}
];
function columnTemplateFunction(dataItem) {
var input = '<input class="dropDownTemplate"/>'
return input
};
function onDDLChange(e) {
var element = e.sender.element;
var row = element.closest("tr");
var grid = $("#memberNotInit-grid").data("kendoGrid");
var dataItem = grid.dataItem(row);
dataItem.set("Status", e.sender.value());
//alert(e.sender.value());
if (dataItem.Status == #((int)DriverRandomPoolStatus.Active)) {
$.ajax({
method: "POST",
url: "#Html.Raw(Url.Action("ChangeMemberStatus", "RandomPoolInit"))",
data: { id: dataItem.Id, status: dataItem.Status }
}).done(function () {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").hide();
grid.pager.refresh();
});
}
if (dataItem.Status == #((int)DriverRandomPoolStatus.Excused)) {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.reasonTemplate').show();
var ddl = grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.dropDownTemplate');
//ddl.value(dataItem.Status);
}
};
function reasonChange(event) {
if (event.keyCode === 13) {
var element = event.target;
var row = element.closest("tr");
var grid = $("#memberNotInit-grid").data("kendoGrid");
var dataItem = grid.dataItem(row);
var r = grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.reasonTemplate').val();
$.ajax({
method: "POST",
url: "#Html.Raw(Url.Action("ChangeMemberStatus", "RandomPoolInit"))",
data: { id: dataItem.Id, status: dataItem.Status, reason: r }
}).done(function () {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").hide();
grid.pager.refresh();
});
}
}
});
</script>
but when we select "Exclused" from dropdownlist value of dropdownlist is dumped to Enrollment (first value from dropdownlist). Why so and how to fix it?
I fixed it the following way:
$(ddt).kendoDropDownList({
value: dataItem.Status,
.....
});
not:
value: dataItem.value,

jqgrid does not fire when the ENTER key gets pressed

I need to trap when the user presses ENTER in edit mode and this code works every time any other key gets pressed but not ENTER.
Any ideas why? maybe there is an automatic setting that needs to be set to false?
$(dispgrid).jqGrid({
url: als.common.getServerPath() + 'WorkorderAjax/GetDispositionFields',
datatype: 'local',
mtype: 'POST',
height: 292,
width: 480,
caption: 'Disposition Instructions',
hidegrid: false,
loadtext: 'Please wait,</br>loading disposition fields...',
colModel: [
{ name: 'Description', label: 'Description', sortable: false, width: 120, align: 'left' },
{ name: 'Fraction', label: 'Split', sortable: false, width: 40, align: 'center' },
{
name: 'Disposition', label: 'Disposition', sortable: false, align: 'left',
editable: true, edittype: 'select', classes: 'disposition_list'
},
{ name: 'PickList', label: 'PickList', sortable: false, hidden: true },
{
name: 'FreeDays', label: 'FreeDays', sortable: false, editable: true
},
{ name: 'MaxFreeDays', label: 'MaxFreeDays',hidden: true }
],
pgbuttons: false,
pginput: false,
rowNum: 999,
loadComplete: function () {
currentRowId = undefined;
prevRowId = undefined;
prevRowModified = false;
},
onSelectRow: function (rowId) {
if (prevRowId !== undefined) {
if (prevRowModified) {
//validate free days here
var selRowId = $(dispgrid).jqGrid('getGridParam', 'selrow');
var freedays = $("#" + prevRowId + "_FreeDays", dispgrid).val();
var maxfreedays = $(dispgrid).jqGrid('getCell', selRowId, 'MaxFreeDays');
if (parseInt(freedays) > parseInt(maxfreedays)) {
$(dispgrid).jqGrid('restoreRow', selRowId);
showErrorDialog("Free days can not be larger than " + maxfreedays);
$(dispgrid).resetSelection();
$(dispgrid).setSelection(prevRowId, false);
return true;
}
saveparameters = {
url: als.common.getServerPath() + 'WorkorderAjax/UpdateDispositionFields',
extraparam: {
folderno: wo,
fraction: prevRowId,
disposition: $('#' + prevRowId + '_Disposition', this).val(),
freedays: $('#' + prevRowId + '_FreeDays', this).val()
},
successfunc: function () {
$(this).trigger("reloadGrid");
prevRowModified = false;
$(this).restoreRow(prevRowId);
return true;
}
};
$(this).jqGrid('saveRow', prevRowId, saveparameters);
}
else {
$(this).restoreRow(prevRowId);
}
}
currentRowId = rowId;
var rowData = $(this).jqGrid('getRowData', currentRowId);
var unformatted = rowData.PickList;
var formatted = '';
var ar = unformatted.split(',');
for (var i = 0; i < ar.length; i++) {
formatted += ar[i] + ':' + ar[i]
+ (i < ar.length - 1 ? ';' : '');
}
$(this).setColProp('Disposition', { editoptions: { value: formatted } });
saveparameters = {
url: als.common.getServerPath() + 'WorkorderAjax/UpdateDispositionFields',
extraparam: {
folderno: wo,
fraction: currentRowId,
disposition: $('#' + currentRowId + '_Disposition', this).val()
},
successfunc: function () {
$(this).trigger("reloadGrid");
prevRowModified = false;
return true;
},
keys: true
};
$(this).editRow(currentRowId, saveparameters);
prevRowId = currentRowId;
}
}).closest('div.ui-jqgrid-view').children('div.ui-jqgrid-titlebar').css('text-align', 'center').
children('span.ui-jqgrid-title').css('float', 'none');
$(dispgrid).on('change', '', function () { prevRowModified = true; });
$(dispgrid).on('keydown', '', function (e) {
//the break point here gets hit every time unless the user presses ENTER key
if (e.keyCode == 13) {
}
});
keys:false in the saveparameters did the trick

How to retrieve a text value in a kendo drop down list within a kendo grid cell but still pass the ID in CRUD

I'm having a problem finding a solution related to the Kendo Grid.
I am rendering a kendo dropdown list within a cell of a Kendo Grid. It appears to look fine and all, until the user focuses off or tabs off of the dropdown within the cell. The red hash shows that a change was made, but it's showing the data-value-field of the kendo DDL and not the text. Ok, I realize I can just use the same field from the DS in the dataTextField as I'm using in the dataValueField, but that won't work for me...because when I'm calling create or update, I need to be able to pass the primary key or ID of that selected item back into my web api controller.
Here is the grids DS
function loadContactGrid(vendorID) {
var contactsReadURL = null;
contactsReadURL = "/contacts/getcontacts/" + parseInt(vendorID);
contactGridDS = new kendo.data.DataSource({
transport: {
read: {
url: contactsReadURL,
type: 'GET',
contentType: "application/json; charset=utf-8",
},
update: {
url: "/contacts/UpdateContacts/",
type: 'PUT',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(xhRequest, ErrorText, thrownError) {
alert('ERROR!!!\n' + ' xhRequest: ' + xhRequest + '\n' + ' ErrorText: ' + ErrorText + '\n' + ' thrownError: ' + thrownError + '\n');
},
complete: function(e) {
$("#contactGrid").data("kendoGrid").dataSource.read();
}
},
destroy: {
url: "/contacts/DeleteContact/",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "DELETE"
},
create: {
url: "/contacts/InsertContact/",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: "json",
success: function(results) {
alert('Contacts successfully saved!');
},
error: function(xhRequest, ErrorText, thrownError) {
alert('ERROR!!!\n' + ' xhRequest: ' + xhRequest + '\n' + ' ErrorText: ' + ErrorText + '\n' + ' thrownError: ' + thrownError + '\n');
},
complete: function(e) {
$("#contactGrid").data("kendoGrid").dataSource.read();
}
},
parameterMap: function(options, operation) {
if (operation !== "read" && options) {
return JSON.stringify(options.models);
}
if (operation == "create") {
// send the created data items as the "models" service parameter encoded in JSON
return { models: kendo.stringify(data.models) };
}
}
},
batch: true,
scrollable: false,
pageSize: 8,
change: function(e) {
if (e.action == "itemchange" && e.field == "email") {
var model = e.items[0];
if (isEmailValid($('input[name=email]').val()) == false) {
e.items[0].receivereport = false;
}
}
if (e.action == "itemchange" && e.field == "contacttype") {
var model = e.items[0];
//setTimeout(function () {
//$('.k-dirty-cell').focusout(function() {
//alert($(this).text(textOverrideContactType(e.items[0].contacttype)));
//});
//textOverrideContactType(e.items[0].contacttype);
//}, 1000); attempting to change text in cell here failed
}
if (e.action === "remove") {
this.sync();
}
},
schema: {
model: {
id: 'contactid',
fields: {
roletyp_seq: { editable: false, nullable: false, required: true, type: 'string' },
contacttype: { editable: true, nullable: false, required: true, type: 'number' },
roletyp_pk: { editable: false, nullable: false, required: true, type: 'number' },
contactid: { editable: false, nullable: false, required: true, type: 'number' },
vendorid: { editable: false, nullable: false, required: true, type: 'number' },
prevrole_pk: {
editable: false,
nullable: true,
required: true,
type: "number",
}
}
}
},
});
And my grid
$("#contactGrid").kendoGrid({
dataSource: contactGridDS,
navigatable: true,
dataBound: mapContactTypes,
editable: true,
//editable: "inline",
//editable: "popup",
edit: function (input) {
if ($('input[name=receivereport]').is(':focus')) {
//detect if email is valid
//get input immediately before this one
if (isEmailValid($('input[name=receivereport]').parent().prev().text()) == false) {
// disable check box
// alert("invalid");
$('input[name=receivereport]').attr('disabled', 'true');
$('input[name=receivereport]').prop('checked', false);
} else {
// enable check box
// alert("valid");
$('input[name=receivereport]').removeAttr('disabled');
$('input[name=receivereport]').prop('checked', false);
}
}
//when user clicks into or out of a field, if the name in the respective row name is blank, alert the user
var grid = this;
var fieldName = grid.columns[input.container.index()].field;
if (isNameInContactGridPopulated(fieldName) == false) {
alert("You can't leave out a contact name in the row you are editing.");
//disable save button
$('.k-grid-save-changes').addClass('k-state-disabled');
$('.k-grid-save-changes').hide();
} else {
//do nothing
$('.k-grid-save-changes').removeClass('k-state-disabled');
$('.k-grid-save-changes').show();
}
if ($('input[name=contactname]').is(":focus") == true) {
//disable save button
if ($('input[name=contactname]').val() == '') {
$('.k-grid-save-changes').addClass('k-state-disabled');
$('.k-grid-save-changes').hide();
}
}
$('input[name=contactname]').keyup(function() {
if ($(this).val() == '') {
$('.k-grid-save-changes').addClass('k-state-disabled');
$('.k-grid-save-changes').hide();
}
});
$('input[name=contactname]').focusout(function () {
if ($(this).val() != '') {
$('.k-grid-save-changes').removeClass('k-state-disabled');
$('.k-grid-save-changes').show();
}
});
},
toolbar: ["save", "cancel"],
pageable: true,
columns: [
{ field: 'roletyp_seq', title: 'RT Seq.', hidden: true, attributes: { 'class': 'contactCell_roletyp_seq' } },
{ field: 'contacttype', title: 'Contact Type', hidden: false, attributes: { 'class': 'contactCell_contacttype' }, editor: loadContactTypeEditor, width: "200px", template: "#=textOverrideContactType(1)#" },
//{ field: 'contacttype', title: 'Contact Type', hidden: false, attributes: { 'class': 'contactCell_contacttype' }, editor: loadContactTypeEditor, width: "200px", template: "#=textOverrideContactType(contacttype)#" },
//{ field: 'contacttype', title: 'Contact Type', hidden: false, attributes: { 'class': 'contactCell_contacttype' }, editor: loadContactTypeEditor, width: "200px" },
{ field: 'prevrole_pk', title: 'prev role ID', hidden: true, attributes: { 'class': 'contactCell_prevrole_pk' } },
{ field: 'roletyp_pk', title: 'Role Type ID', hidden: true, attributes: { 'class': 'contactCell_roletyp_pk' } },
{ field: 'contactid', title: 'Contact ID', hidden: true, attributes: { 'class': 'contactCell_contactid' } },
{ field: 'vendorid', title: 'Vendor ID', hidden: true, attributes: { "class": 'contactCell_vendorid' } },
{ field: 'contactname', title: 'Name', hidden: false, attributes: { "class": 'contactCell_contactname' } },
{ field: 'workphone', title: 'Phone', hidden: false, attributes: { "class": 'contactCell_phone' } },
{ field: 'mobilephone', title: 'Cell', hidden: false, attributes: { "class": 'contactCell_mobilephone' } },
{ field: 'title', title: 'Title', hidden: false, attributes: { "class": 'contactCell_title' } },
{ field: 'email', title: 'Email', hidden: false, attributes: { "class": 'contactCell_email' } },
{ field: 'receivereport', title: 'Receive Reports?', hidden: false, attributes: { "class": 'contactCell_receivereport' }, template: '<input type="checkbox" #= receivereport ? "checked=checked" : "" # value="" disabled="disabled" ></input>' },
{ command: "destroy", title: " ", width: "100px" }
],
sortable: {
mode: 'single',
allowUnsort: false
}
});
Then, I have two functions below. 1 is the custom editor and the other is an attempt I considered to override the text displayed in the kendo ddl.
function loadContactTypeEditor(container, options) {
var contactTypeDS = new kendo.data.DataSource({
dataType: "json",
type: "GET",
transport: {
read: "/contacts/GetAllContactTypes/"
}
});
contactTypeDS.read();
$('<input class="contactTypeDropDown" required data-text-field="roletyp_dsc" data-value-field="roletyp_pk" data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
dataTextField: "roletyp_dsc",
dataValueField: "roletyp_pk",
autoBind: false,
select: function (e) {
//if (e.sender.text() != '') {
// $('#contactGrid_active_cell').html(e.sender.text());
//}
//if (e.sender.text() != '') {
// setTimeout(function() {
// $('.contactCell_contacttype').text(e.sender.text());
// }, 1000);
//}
//options.model[options.field] = e.sender.text();
},
//dataBound: function(){
// options.model[options.field] = e.sender.text();
//},
dataSource: contactTypeDS
});
}
function textOverrideContactType(roleId) {
//need to find a match on the passed in role/contact type ID and return it's match to "mask/overwrite" the text that's there after a user selects an item in the dropdown
$.ajax({
dataType: 'json',
type: 'GET',
url: "/contacts/GetAllContactTypes/",
contentType: 'application/json; charset=utf-8',
success: function (data) {
$.each(data, function (key, val) {
if (roleId == key) {
return val;
}
});
},
failure: function (error) {
alert("Error loading contact types.");
}
});
}
To summarize: I tried a few things with no avail. What is happening, is, the DDL renders just fine, and even when the user doesn't move off of that DDL, the proper "label" shows, but when that control loses focus, it shows the data-value-field. I can't have that, I need to be able to show the data-text-field. That's why I wrote that textoverride method. But I'm trying to call it within the grid, fields's template: and it's not working. It says it doesn't recognize that function. I don't get it; it's clearly declared. What am I supposed to pass in as the parameter, it's not exactly like the demo here...a bit different, as I'm populating the DDL with another remote data source.
http://demos.telerik.com/kendo-ui/grid/editing-custom
Here's the other thing; I need that data-value-field, ID, to persist and be passed into my web api controller when it gets called. Right now, as it stands, I'm only able to get the "text" to show in the controller and not the "ID." That ID will not be available to me in the read method. The stored procs that the CRUD is hitting is completely different. My stored proc for insert and update needs to get that contacttype ID as the number.
Thanks in advance. I'm sure I'm close...
From the provided information it seems that you need to make the column ForegnKey by setting the "values" option of the column. Please check the example below:
[demo] Grid: ForeignKey column
[documentation] Grid API: columns.values option
I actually ended up using another means to do this. The above still seems illusive to me. I ended up changing the values of a key in another row, that was already available, to get passed back into the controller. I tried the answers provided with no avail. Sorry!

Kendo UI toolbar buttons

I am using a Kendo UI grid, which looks like this:
function refreshGrid()
{
$(".k-pager-refresh.k-link").click();
}
var editWindow;
var fields= {FullName: {type: "string"}, Email: {type: "string"}, LogCreateDate: {type: "date"}};
var gridColumns =
[{
width: 90,
command: {
name: "edit",
text: "Edit",
click: function(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
editWindow = $("#edit").kendoWindow({
title: "Edit User",
modal: true,
visible: false,
resizable: false,
width: 800,
height: 400,
content: 'myediturl' + dataItem.ID
});
editWindow.data("kendoWindow").center().open();
return false;
}
}
},
{
width: 90,
command: {
name: "delete",
text: "Delete",
click: function(e) {
//alert(this.dataItem($(e.currentTarget).closest("tr")).ID);
var id = this.dataItem($(e.currentTarget).closest("tr")).ID;
if (confirm("Are you sure you want to delete this user?"))
{
$.ajax({
type: 'POST',
url: '#Url.Action("deleteuser","admin",null, "http")' + "/" + this.dataItem($(e.currentTarget).closest("tr")).ID,
success: function (param) { refreshGrid(); },
async: false
});
}
return false;
}
}
},
{
field: "FullName",
title: "Full Name",
type: "string"
},
{
field: "Email",
title: "Email",
type: "string"
},
{
field: "LogCreateDate",
title: "Created",
type: "date",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
}];
//getSorts the columns of the grid
function getColumns() {
//Parsing the set of columns into a more digestable form
var columns = "";
for (var col in gridColumns) {
if (!!gridColumns[col].field)
{
if (columns.length > 0) {
columns += ";";
}
columns += gridColumns[col].field + "," + gridColumns[col].type;
}
}
return columns;
}
function getSorts(sortObject) {
if (!(sortObject)) {
return "";
}
//Getting the row sort object
var arr = sortObject;
if ((arr) && (arr.length == 0)) {
return "";
}
//Parsing the sort object into a more digestable form
var columnSet = getColumns();
var returnValue = "";
for (var index in arr) {
var type = "";
for (var col in gridColumns) {
if (gridColumns[col].field === arr[index].field) {
type = gridColumns[col].type;
}
}
returnValue += ((returnValue.length > 0) ? (";") : ("")) + arr[index].field + "," + (arr[index].dir === "asc") + "," + type;
}
return returnValue;
}
var grid;
$(function () {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "mydatasourceurl",
type: "POST",
},
parameterMap: function (data, type) {
data.filters = JSON.stringify(data.filter);
data.columns = JSON.stringify(getColumns());
data.sorts = JSON.stringify(getSorts(data.sort));
console.log(data);
return data;
}
},
schema: {
fields: fields,
data: "Data",
total: "Total"
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
toolbar: [{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}],
height: 392,
groupable: false,
sortable: true,
filterable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: gridColumns
});
grid = $("#grid").data("kendoGrid");
});
My create toolbar action is not triggered on click. How can I resolve this problem, is Kendo UI able to handle toolbar click events? The best solution I came up with looks like this:
$(".k-button.k-button-icontext.k-grid-add").click(function () {
//If the window doesn't exist yet, we create and initialize it
if (!grids[gridContainerID].addWindow.data("kendoWindow")) {
grids[gridContainerID].addWindow.kendoWindow({
title: "Add " + entityName,
width: "60%",
height: "60%",
close: onClose,
open: onAddOpen,
content: addUrl
});
}
//Otherwise we just open it
else {
grids[gridContainerID].addWindow.data("kendoWindow").open();
}
//Centralizing and refreshing to prepare the layout
grids[gridContainerID].addWindow.data("kendoWindow").center();
grids[gridContainerID].addWindow.data("kendoWindow").refresh();
return false;
});
Thanks in advance.
Instead of using that complex selector use the one that Kendo UI creates from name:
toolbar: [
{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}
],
and then:
$(".k-grid-Add", "#grid").bind("click", function (ev) {
// your code
alert("Hello");
});
In kendogrid docs here shows that there is no click configuration for grid toolbar buttons like grid.colums.commands.
To solve this problem you can reference following steps:
create a template for toolbar
<script id="grid_toolbar" type="text/x-kendo-template">
<button class="k-button" id="grid_toolbar_queryBtn">Query</button>
</script>
apply tempate to toolbar
toolbar:[{text:"",template: kendo.template($("#grid_toolbar").html())}]
add event listener to button
$("#grid_toolbar_queryBtn").click(function(e) {
console.log("[DEBUG MESSAGE] ", "query button clicked!");
});

Resources