Initialize and load Kendo Grid from JQuery - javascript

in my project i want to initialize Kendo Grid from jquery file. i have created a .js file in which i have created a function
function initializeGrid(gridName, url, onSelectFunction) {
onSelectFunction = onSelectFunction || null;
$("#" + gridName).kendoGrid({
dataSource: {
type: "json",
transport: {
read: url
},
schema: {
model: {
fields: {
ClientID: {type: "number"},
Client:{type: "string"}
}
}
},
pagesize: 30,
Paging: true,
Filtering: true,
},
selectable: "multiple cell",
filterable: true,
columns: [
{ field: "ClientID" },
{ Template: ("<input type='checkbox' id='#:data.ClientID#' class='k-checkbox'/><label class='k-checkbox-label' onclick='event.stopPropagation()' for='#:data.ClientID#'></label>") },
{ field: "Client" }
]
});
$("#" + gridName).attr("data-val-number", "Invalid input.");
}
this function accepts name of the control and url to load data source from as arguments. in another .js file i have all code that loads controls by calling the earlier function.
initializeGrid("client", "/Clients/GetDataForGrid", null);
issue is that when i run the program it is not creating the grid and loading the data instead showing a drop down with no data. i checked http://docs.telerik.com/kendo-ui/api/javascript/ui/grid?utm_medium=social-owned&linkId=38973492 for reference but no use.
i would really appreciate help here.

Related

jQuery kendo grid popup editor doesn't pass dropdown values to .net MVC controller?

I am trying to edit a row in jquery kendo grid popup editor. But when I click on update button it does not submit selected dropdown values to the controller while it submits the other properties without any issues. I have tried many examples but nothing works well.
This is my code
var element = $("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: '/controller/GetEmployees',
update: {
url: "/controller/UpdateEmployee",
dataType: "json"
},
},
pageSize: 10,
serverPaging: true,
serverSorting: false,
schema: {
model: {
id: "EmployeeID",
fields: {
EmployeeID: { type: "number", editable: false },
EmployeeName: { type: "string", editable: true },
EmployeeStatus: { defaultValue: { ID: 1, Name: "Active" }, editable: true }
}
}
}
},
height: 500,
sortable: false,
pageable: false,
editable: "popup",
toolbar: ["create"],
columns: [
{
field: "EmployeeName",
title: "Employee Name",
width: "110px"
},
{
field: "EmployeeStatus",
title: "Status",
width: "110px",
editor: activeInactiveDropDownEditor,
template: "#=EmployeeStatus.Name#"
},
{
command: "edit",
width: "80px"
}
]
});
});
}
function activeInactiveDropDownEditor(container, options) {
$('<input required name="' + options.field + '" data-bind="ID"/>')
.appendTo(container)
.kendoDropDownList({
//autoBind: true,
dataTextField: "Name",
dataValueField: "ID",
dataSource: {
type: "json",
transport: {
read: "/controller/GetStatusList"
}
}
});
}
could anyone found the fault here please ?
Finally I found a solution. I just modified update request with a type property and it works well now.
update: {
type: 'post', // just added this and works well
url: "/controller/UpdateEmployee",
dataType: "json"
},
I think your problem is with the binding, I mean, it is not just add a data attribute bind with the field name, sometimes binding models to widgets needs some level of complexity. As I can't reproduce your whole snippet, I would suggest you to use options.model to set the input value, hence the widget can initialize with the right value:
function activeInactiveDropDownEditor(container, options) {
$('<input required name="' + options.field + '" value="' + options.model.ID + '" />')
If that doesn't works, set the value init parameter or anything like that.

Kendo UI Listi View not updating data on the server

I am having trouble saving changes using to the server using Kendo UI Listview.
The DataSource is configured like this:
var listViewDataSource = new kendo.data.DataSource({
transport: {
read: {
url: MyServiceURL
},
update: function() {
console.log("test"); // I expected to enter this function
// when the user changes data on the
//client, never happens
}
},
schema: {
Id: "Id",
fields: {
DeptName: {
editable: false,
},
HourRate: {
type: "number",
editable: true
},
ShowOnSavings: {
type: "boolean",
editable: true
},
ShowOnTechnicalCosts: {
type: "boolean",
editable: true
},
ShowOnOtherCosts: {
type: "boolean",
editable: true
}
}
},
sync: function (e) {
console.log("item synched"); //This should be fired after the
// updated data is sent, never
//happens
}
The ListView is initialised like this:
kendo.bind($("#listview-container"), {
listViewDataSource: listViewDataSource,
onItemSaved: function (e) {
console.log("item saved"); // fired every time the user changes
//an item, as expected
}
})
The ListView properly loads the data. When the user edits an item the change is visible locally (after leaving edit mode) and the save event is fired, as expected.
However the changes are never synchronized with the server, my update method is never called and no network activity is never called.
The documentation on the ListView save method states the following:
Saves edited ListView item. Triggers save event. If save event is not prevented and validation succeeds will call DataSource sync method.
As I don't call preventDefaulton the save event I expect the data sourve to sync, however this does not happen. Calling dataSource.sync() manually does not help either.
I am puzzled why this does not work. Any tips appreciated.
I skipped one level of nesting in the model configuration, model was missing
schema: {
model: {
id: "Id",
fields: {
Id: {
type: "number",
editable: false
},
DeptName: {
type: "string",
editable: false
},
HourRate: {
type: "number",
editable: true
},
ShowOnSavings: {
type: "boolean",
editable: true
},
ShowOnTechnicalCosts: {
type: "boolean",
editable: true
},
ShowOnOtherCosts: {
type: "boolean",
editable: true
}
}
}
}

Why Kendo dataSouce.transport.update method do not send data to the server?

I have a Kendo UI TreeList where every row has a checkbox displayed. If the user clicks on the checkbox then a request goes to the server and save the data. Unfortunately, I did something wrong because:
the update method does not send data to the server
and the sync method is not called automatically
What I did wrong?
I think the problem around how I set up that which item has changed. As you can see I iterate over the dataset coming from dataSource.data() and the item.checked and item.dirty properties are updated. If I understand correctly the documentation then this changes should trigger the sync method. It does not trigger the sync method and this it the reason I call it in the method.
My other question is related to the data structure should be sent to the server. It is based on the schema, right? So, once I can achieve that the request sends an object to the server I should create a similar C# POCO as model and I can read the data in the webapi controller.
In the documentation there is a saveRow() method, but I cannot translate that code to angular. Can somebody help me in this case?
//this row is my problem
var treeList = $("#treeList").data("kendoTreeList");
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: configurationService.goNoGoWebApiRootUrl + 'AreaPathDependencies/Get/ChildrenMarked/' + selectedAreaPathIdFromModalService,
dataType: "json",
type: "get"
},
update:
{
url: configurationService.goNoGoWebApiRootUrl + 'AreaPathDependencies/Update/AreaPathDependencies',
dataType: "json",
type: "post"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id: "id",
parentId: "parentId",
fields: {
Id: { type: "number", editable: false, nullable: true },
ParentId: { type: "number", editable: false, nullable: true },
Name: { type: "string", editable: false, nullable: true },
Checked: { type: "boolean", editable: true, nullable: false }
}
}
}
});
vm.treeListOptions = {
dataSource: dataSource,
sortable: false,
editable: false,
columns: [
{
field: "checked",
title: "Selected",
template: checkBoxTemplate,
width: 32
},
{ field: "name", title: "Area Path", width: "200px", expandable: true },
{ field: "fullPath", title: "FullPath", width: "500px" },
],
save: onSave,
change: onChange,
sync: sync,
autoSync: true,
};
}
function checkboxOnclick(selectedId) {
console.log('checkboxOnclick', selectedId);
var data = vm.treeListOptions.dataSource.data();
for (var i = 0; i < data.length; i++) {
if (selectedId == data[i].id) {
data[i].set("checked", true);
//data[i].dirty = true;
}
}
vm.treeListOptions.dataSource.sync();
//console.log('flush', vm.treeListOptions.dataSource.data());
}
Well batch: true has to be set to get parameterMap working, because models parameters will be available only when the batch option is enabled. (parameterMap docs)
And to second question - I am not so sure but as noted in sync docs,
The sync method will request the remote service if:
the transport.create option is set and the data source contains new data items
the transport.destroy option is set and data items have been removed from the data source
the transport.update option is set and the data source contains updated data items
How I understand to that - to get sync method working you need to return updated records. Please check, if your server method for update/delete returns that.

Kendo UI grid filter doesn't work when opening a popup before

I have a Kendo UI grid where some of the columns can be filtered. For each row in that column, you can open a popup to see some details to the specific entry.
I can open the popup without any problems. But: after closing it and trying to filter any of the columns, I get the following error: JavaScript runtime error: Unable to get property 'toggle' of undefined or null reference
If I filter a column before I open a popup, it works like a charm.
If I filter a column and then open the popup, the already filtered column can be filtered again but the others not.
I don't know why I can't filter columns after opening and closing the popup.
Any ideas or hints would be really helpful. Thanks
HTML:
<div id="windoofTestOuter"><div id="windoofTest"></div></div>
<div id="processGrid"></div>
My grid:
$("#processGrid").kendoGrid({
sortable: true,
pageable: true,
selectable: true,
filterable: {
extra: false
},
dataSource: {
type: "aspnetmvc-ajax",
transport: {
read: {
url: "/Home/GetProcesses",
cache: false,
type: "POST",
dataType: "json"
},
parameterMap: function (data) {
return $.extend({}, data, { sort: data.sort, filter: data.filter });
}
},
serverPaging: true,
serverFiltering: true,
serverSorting: true,
page: "#ViewBag.ProcessPage",
schema: { data: "Data", total: "Total", model: { id: "Id" } },
pageSize: "#(#Model.MaxCountToShow)"
},
columns: [
{ field: "ErrorDateTime", title: "ProcessDateTime", width: "170px"/*, filterable: { ui: dateFilter }*/ },
{ field: "Name", title: "Processtype", attributes: { value: "type" }, width: "240px;", filterable: { ui: processtypeFilter} },
{ field: "Service", title: "Service", width: "181px;", filterable: { ui: serviceFilter } },
{ field: "Operation", title: "Operation", width: "130px", filterable: { ui: operationFilter } }
]
}).data("kendoGrid");
The link/string which shall open the popup:
function createProcessActionString(process) {
var det = '<a class="makeANiceMouse" onclick="processDetailUrl(' + process.Id + ', ' + grid.dataSource.page() + ')">Details</a>';
return det;
}
My popup:
function processDetailUrl(id, page) {
var windoof = $("#windoofTest").kendoWindow({
width: "1150px",
height: "300px",
content: det,
title: "Process Details",
actions: ["Minimize", "Maximize", "Close"],
close: function (e) {
windoof.data("kendoWindow").content(" ");
}
});
windoof.data("kendoWindow").center().open();
}
I deleted the unnecessary columns and so on..
EDIT: I tried to intitialize the filter in the filterMenuInit. After opening and closing the popup, I clicked on the filter icon of one of the columns, and I get the error : JavaScript runtime error: Unable to get property 'toggle' of undefined or null reference . The same one as before.
EDIT: I used the windoof.destroy() but the filters weren't accessable afterwards.
EDIT solution: I have a workaround for working with the filters again. I just fake a click on each of it before I open a popup. It's not beautiful but it serves me so far.
BUT It seems like everything gets kicked/killed by that damn popup. I can't even access the grid's datasource anymore.. It's strange...
I'm dealing with the same issues but got well passed the Data not being there. Check out or use onDataBound and use e.sender to get a handle to the Grid Object opposed to .data("KendoGrid") from the onClose of the popup this is what fixed it for me. I'm still trying to get my filters to work though after the pop up closes.

add record function in Kendo UI grid is called many times

I am using this html code for Keno UI grid
function loadPhoneGrid(salesRepsId){
$("#phone-grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "operations/get_phones_sales_reps.php?salesRepsId="+salesRepsId,
type: "GET"
},
update: {
url: "operations/edit_phone_number.php?salesRepsId="+salesRepsId,
type: "POST"
},
destroy: {
url: "operations/delete_phone.php",
type: "POST"
},
create: {
url: "operations/add_phone.php?salesRepsId="+salesRepsId,
type: "POST",
},
},
schema: {
data:"data",
total: "data.length", //total amount of records
model: {
id: "PhoneId",
fields: {
PhoneType: { defaultValue: { PhoneTypeId: 1, PhoneTypeName: "Work"} },
PhoneNumber: { type: "string" },
IsMainPhone: {type: "boolean", editalbe:true},
}
}
},
pageSize: 5,
},
height: 250,
filterable: true,
sortable: true,
pageable: true,
reorderable: false,
groupable: false,
batch: true,
toolbar: ["create", "save", "cancel"],
editable: true,
columns: [
{
field:"PhoneType",
title:"Type",
editor: PhoneTypeDropDownEditor,
template: "#=PhoneType.PhoneTypeName#"
},
{
field: "PhoneNumber",
title:"Phone Number",
},
{
field: "IsMainPhone",
title:"Is Main",
width: 65,
template: function (e){
if(e.IsMainPhone== true){
return '<img align="center" src ="images/check-icon.png" />';
}else{
return '';
}
}
// hidden: true
},
{ command: "destroy", title: " ", width: 90 },
],
});
}
The code in the server side is (add_phone.php)
<?php
require_once("../lib/Phone.php");
$phone = array();
foreach($_POST as $name => $value){
$phone[$name] = $value;
}
Phone::AddPhoneNumber($_GET["salesRepsId"], $phone);
?>
For the first time, I added a new record. add_phone.php is calling once and everything is working fine. For the second time (with out refresh the page) when I try to add a new record, add_phone.php is called twice. One of them contains the first record which has been added to database before and the second is the new the data.
in the result I have 3 records ( 2 same data of first insert) and one new.
This an example to make it clear ( inspect the post request with firebug)
first click on save button (false, (111) 111-1111, 4,Fax) // after I enter this phone (111) 111-1111
second click on save button (false, (111) 111-1111, 4,Fax) in addition to (false, (222) 222-2222, 3,Work) // after I added this (222) 222-2222
Any help ??
May be your ajax request raise an error. You can see it by subscribing to the error event of your datasource.
In case of error, the data are not synchronized in your datasource. In your case, I think your dataitem stay in "dirty mode" so the datasource try to insert them for each synchronization...

Categories

Resources