Telerik Datasource Json Server Paging Not Working - javascript

I'm working on a Hybrid app built with Json data. There's a small problem though. I can't figure out how to get the paging to work for the Datasource.
The json structure looks like this.
{
"respond":1,
"paging":{
"stillmore":1,
"perpage":10,
"callpage":1,
"next":2,
"previous":0,
"pages":6,
"result":"52"
},
"message":"",
"result":[
{Main Data}
]
}
Here's my DataSource structure
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "JsonURL",
dataType: "json",
jsonp: "$callback",
cache: true
},
serverFiltering: true,
filter: { logic: "paging", filters: [ { field: "name", operator: "startswith", value: "Jane" } ] },
parameterMap: function (data, type) {
return kendo.stringify(data);
if (type == "read") {
// send take as "$top" and skip as "$skip"
return {
$callpage: data.page,
$perpage: data.pageSize
}
}
}
},
schema: {
data: "result", // twitter's response is { "results": [ /* results */ ] }
total: "paging.result",
},
sort: {
field: "ID",
dir: "desc"
},
serverPaging: true,
serverSorting: true,
pageSize: 20
});
It's not paging. I have about 100 results, and the server only displays 20 every page. When you want to load the next 20, nothing happens. It gets stuck on the loading gif.
I can't seem to figure it out. How can I enable server paging with this Json return?
Any tips would be welcome! Thanks!

You have mistake in your code in:
parameterMap: function (data, type) {
// DELETE THIS LINE: return kendo.stringify(data);
if (type == "read") {
// send take as "$top" and skip as "$skip"
return {
callpage: data.page,
perpage: data.pageSize
}
}
}
You return return kendo.stringify(data); immediately and you can't use your custom binding for page number.
Try to delete this line as I show you above

Related

Unable To Display Json Data in html Table Using jquery DataTable

i have C# function That Return Me Json Formated Data , function is below
void DisplayProjectMasterList()
{
string JSONString = "";
DataTable Dt = DB.GetDataTable("Sp_GetProjectMasterList");
if (Dt.Rows.Count > 0)
{
JSONString = JsonConvert.SerializeObject(Dt);
}
Context.Response.Write(JSONString);
}
and I am Calling This Function Via Ajax .in console i am getting json data But i dont know how to pass it to Jquery data table to display.. below is the javascript function... please help Me
function DisplayProjectMasterList() {
$.ajax({
url: 'project-master.ashx',
type: "POST",
dataType: 'json',
data: {
'fun': 'DisplayProjectMasterList'
},
success: function (data) {
console.log(data);
if (Chk_Res(data.errorMessage) == false) {
$('#tbl').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
columns: [
{ 'data':data.Prj_Id },
{ 'data':data.Prj_No },
{ 'data':data.Prj_Name },
{ 'data':data.Cus_Company_Name },
{ 'data':data.Prj_StartDate },
{ 'data':data.Prj_CompletionDate },
]
});
}
}
});
}
i am Getting FOllowing error while doing So:
DataTables warning: table id=tbl - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Hi make sure the data you are being returned is in the following format:
{
"data": [
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
},
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
}
]
}
jquery Datatables by default looks for data property for the array of objects
https://datatables.net/reference/option/ajax.dataSrc
https://datatables.net/examples/ajax/objects.html

How can i do server side Sorting in JSGrid

I have implemented jsGrid and did the Filtering server side.Now i want to send sorting parameter to server side and do the sorting on server side on the click of column.
This is how i implemented the grid -
var db = {
loadData: function(filter) {
var bFilter = [];
var d = $.Deferred();
console.log("sorting:", filter.sortField, filter.sortOrder);
for (var prop in filter) {
if (prop != "sortField" && prop != "sortOrder") {
bFilter.push({
"Name": prop,
"Value": filter[prop]
})
} else{
var sorting ={ "Name": filter["sortField"], "Type": filter["sortOrder"] };
}
}
$.ajax({
url: "http://abc/abc",
dataType: "json",
data: JSON.stringify({
"filter": bFilter,
"sorting": sorting
})
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
},
};
$("#jsGrid").jsGrid({
height: 300,
width: "100%",
filtering: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 2,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete the client?",
controller: db,
fields: [{
name: "Name",
type: "text",
width: 150
},
{
name: "Age",
type: "number",
width: 50
},
{
name: "Address",
type: "text",
width: 200
},
{
type: "control"
}
]
});
How would i call the same loaddata method on click of header for sorting to do the filtering and sorting together on server side.
How to disable the client side sorting and do it on serve side same like filtering.
If i set sorting:false it removes the click from the column headers.I want to keep that as well.
I was able to solve this by changing the sort function -
jsGrid.loadStrategies.DirectLoadingStrategy.prototype.sort = function () {
var filters = $("#tableId").jsGrid("getFilter");
var sorting = $("#tableId").jsGrid("getSorting");
this._grid.controller.loadData(filters, sorting);
}

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.

Unable to sort jqGrid column with sorttype function

Trying to sort a grid with custom sort. I am building jqgrid with dynamic columns and data. Everything works well except sorting of one of the column. I am using javax.json to build the json and I am using jqgrid 4.7.0. Here is the grid code:
var resultsGrid = $("#resultsGrid");
var url = "grid/GridDataController?action=runSearch&searchText="+getSearchText()+"&_ts"+$.now();
var csvUrl = "grid/GridDataController?action=downloadCsv&_ts"+$.now();
var gridPagerId="#resultsPager";
var drawSearchResultsGrid = function(colNames,colModel,data) {
resultsGrid.disableSelection(); //disales highlioghting cells outside selection like ghosting.
resultsGrid.jqGrid({
url: url,
datatype: 'jsonstring',
loadonce: true,
mtype: "GET",
height: 300,
width: 700,
colNames: colNames,
colModel: colModel,
datastr : data,
rowNum: 100000,
sortname: "invid",
sortorder: "asc",
rownumbers: true,
viewrecords: true,
pager: gridPagerId,
pginput : false,
pgbuttons : false,
viewrecords : false,
gridview: true,
autoencode: true,
onSelectRow : function(id) {
logMessage("row selected ["+id+"]");
},
loadComplete: function(data) {
logMessage("load completed");
},
ondblClickRow : function(rowid) {
logMessage("Double clicked");
$(escapeColon("#contentForm:viewPropertiesButton")).click();
}
});
// Set navigator with search enabled.
resultsGrid.jqGrid('navGrid',gridPagerId,{add:false,edit:false,del:false,search:false,refresh:false});
// add custom button to export the data to excel
resultsGrid.jqGrid('navButtonAdd',gridPagerId,{
caption:"Export",
onClickButton : function () {
resultsGrid.jqGrid('excelExport',{"url":csvUrl});
}
});
}; //end drawResultGrid function
//get grid config...
$.ajax({
type: "GET",
url: url,
data: "",
dataType: "json",
success: function(response)
{
if (response.result == "0")
{
logMessage("Drawing results grid...");
drawSearchResultsGrid(response.colNames,response.colModel,response.data);
resizeGrid();
logMessage("Results grid drawing done.");
}
else
{
logMessage("Error : " + response.message);
alert(response.message);
}
},
error: function(x, e)
{
alert(x.readyState + " "+ x.status +" "+ e.msg);
}
});
Here is my dynamic colModel looks like:
{
"result":"0",
"message":"",
"data":{
"records":18,
"total":1,
"page":"1",
"rows":[ ]
},
"colNames":[
"IP Address/Cidr",
"Name",
"IP Decimal",
"Cidr"
],
"colModel":[
{
"name":"adressCidr",
"width":50,
"sortable":true,
"hidden":false,
"sorttype":"function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']'); return parseInt(rowObject.ipDecimal,10);}"
},
{
"name":"name",
"width":50,
"sortable":true,
"hidden":false
},
{
"name":"ipDecimal",
"width":50,
"sortable":true,
"hidden":false,
"sorttype":"int"
},
{
"name":"cidr",
"width":0,
"sortable":false,
"hidden":true
}
]
}
ipDecimal is a hidden column but I am displaying it for testing purpose. Requirement is first column 'addressCidr' is a string column but i want to sort it using hidden ipDecimal column. The function neither does show console.log message nor does any sorting properly. However, If i sort by ipDecimal with sorttype as 'int' by clicking on its header, it works fine. Only thing i can think of is the double quote around the sorttype function itself. Please let me know if you see any other issue here, or what is the best way to solve this case. Here is snippet where I build json function:
private JsonObjectBuilder createColumn(JsonBuilderFactory factory,
String name,int width,boolean sortable,boolean hidden,boolean sorttype)
{
JsonObjectBuilder column =this.createColumn(factory, name, width, sortable, hidden);
StringBuilder fnBuilder = new StringBuilder("");
//this is not generic but can easily be made one :(
fnBuilder.append("function (cellValue,rowObject) {");
fnBuilder.append(" console.log('sorting by ['+rowObject.ipDecimal+']');");
fnBuilder.append(" return parseInt(rowObject.ipDecimal,10);");
fnBuilder.append("}");
column.add("sorttype", fnBuilder.toString()); // this works, not sure why above function does not work :(
return column;
}
private JsonObjectBuilder createColumn(JsonBuilderFactory factory,
String name,int width,boolean sortable,boolean hidden)
{
JsonObjectBuilder column;
column = factory.createObjectBuilder();
column.add("name", name);
column.add("width", width);
column.add("sortable", sortable);
column.add("hidden", hidden);
return column;
}
Data I used for testing is:
IpAddressCidr ipDecimal
5.1.0.0/24--83951616
5.1.1.0/24--83951872
5.1.2.0/24--83952128
5.1.3.0/24--83952384
5.1.4.0/24--83952640
5.3.0.0/24--84082688
5.9.2.0/24--84476416
6.0.0.0/24--100663296
6.0.1.0/24--100663552
6.0.2.0/24--100663808
6.0.3.0/24--100664064
6.0.4.0/24--100664320
6.0.5.0/24--100664576
7.1.0.0/24--117506048
7.1.1.0/24--117506304
7.1.2.0/24--117506560
7.1.3.0/24--117506816
198.186.198.0/24--3334129152
But here is that I see
Ip 198.186.198.0 should have appeared at the top as it has highest ipDecimal, but it gets pushed to the bottom.
To add more test information. If I remove enclosed double quotes, sort works fine, but not with it.
Following works:
{ name: "adressCidr", width:50, sortable: true,
sorttype: function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']');return parseInt(rowObject.ipDecimal,10);}},
Following does not:
{ name: "adressCidr", width:50, sortable: true,
sorttype: "function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']');return parseInt(rowObject.ipDecimal,10);}"},
The reason of your problem is the usage of sorttype which you defines as string instead of function:
{
"name":"adressCidr",
"width":50,
"sortable":true,
"hidden":false,
"sorttype":"function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']'); return parseInt(rowObject.ipDecimal,10);}"
}
You use jqGrid 4.7 which contains new feature which I suggested (see here). So you can include the code like
$.extend($.jgrid, {
cmTemplate: {
myIpAddress: {
sorttype: function (cellValue, rowObject) {
console.log('sorting by [' + rowObject.ipDecimal + ']');
return parseInt(rowObject.ipDecimal, 10);
},
width: 50
}
}
});
Now you can change the data returned from the server to
{
"name":"adressCidr",
"sortable":true,
"hidden":false,
"template":"myIpAddress"
}

Lazy Load with Scrollable {Virtual:true} not working in Kendo UI Grid

I am facing an issue to implement lazy loading in kendo ui grid.
I added scrollable virtual property and backend server side code to handle it but issues is after adding scrollable property I am unable to see scroll bar in my Grid.
Even the selected rows (20 page size) disappears off the bottom of the grid into the hidden overflow area.
Here is my code.
var managecustomerGrid = $("#customerGrid").kendoGrid({
dataSource: {
schema: {
data: "results",
total : "totalRecords",
model: {
id: "SRNUMBER",
fields: {
SRNUMBER : {type: 'number'},
CUSTOMERNAME : {type: 'string'},
DATEPAID : {type: 'string'}
}
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 20,
batch: false,
transport: {
read: {
type: "POST",
url: "/customer/customer.cfc",
dataType: "json",
error: function (xhr, error) {
alert('Error In Getting Customer Information.');
}
},
parameterMap: function(options, type) {
return {
ntPageNumber: options.page,
ntRowLimit: options.pageSize,
vcSortOrder: JSON.stringify(options.sort),
vcFilterCondition: JSON.stringify(options.filter)
}
}
}
},
toolbar: kendo.template($("#template").html()),
height: 600,
scrollable: {
virtual: true
},
filterable: {
operators: {
string: {
contains: "Contains",
startswith: "Starts with",
endswith: "Ends with",
eq: "Is equal to",
doesnotcontain: "Doesn't contain"
}
}
},
sortable: true,
columns: [
{ field: "SRNUMBER", title: "SR No.", width: "80px", template: "<span id='#=SRNUMBER#'>#=SRNUMBER#</span>"},
{ field: "CUSTOMERNAME", title: "Customer Name", width: "110px"},
{ field: "DATEPAID", title: "Date", width: "110px"},
{ command: ["edit","detail","cancel"], title: " ", title: "Actions", width: "130px", filterable: false, sortable: false}
]
});
Please let me know if any one find any issues. I am unable to get it.
The kendo grid does not really support Lazy Loading out of the box. It may be easier to instead just make a blank scroll-able grid (without paging), and then to populate the data with ajax calls. You can use $.merge() to append data to the data array with little to no impact on performance.
$.ajax({
url: '/getNextData',
data: { filter: 'foo', lastLoaded: $("#Grid").data("kendoGrid").dataSource.at($("#Grid").data("kendoGrid").dataSource.total()-1).ID },
dataType: "json",
success: function (newData) {
$("#Grid").data("kendoGrid").dataSource.data($.merge($("#Grid").data("kendoGrid").dataSource.data(), newData))
},
error: function (e) { console.log(e); }
});
In this ajax example I load the next data based on the current last item in the grid and a filter. I just append the response to the currently loaded data.
I faced the same issue, my problem was the controller code. Here I am posting my controller hoping it would help someone someday
public JsonResult GetJson(int? projectid,int skip, int take, int pageSize, int page)
{
using (sqlCon)
{
var myData = sqlCon.Query<Device>("Select * from workbook.dbo.TargetList", new { projectid = projectid });
var data = myData .Skip(skip).Take(pageSize).ToList();
var total = myData .Count();
var json = new { data = myData };
var jsonResult = Json(new {data= data, total= total}, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
}

Categories

Resources