Cannot Paginate using Kendo UI and Web API - asp.net

I am a complete novice in KendoUI so this might seem like a noob question.
I am trying to implement server side pagination using KendoUI and Web API.
This is my script for generating the Kendo Grid
$(function () {
$("#grid").kendoGrid({
height: 400,
columns: [
"FirstName",
"LastName",
{ field: "Mobile", width: "150px" },
{ field: "Email", width: "150px" },
{ field: "LoginVerified", width: "150px" },
{ field: "DivisionName", width: "100px" }
],
pageable: true,
sortable: true,
filterable: true,
dataSource: {
serverPaging: true,
serverFiltering: true,
serverSorting: true,
pageSize: 10,
transport: {
read: "/api/Users/GetStaffsPaged"
}
}
});
});
And this is my Web API function
[HttpGet]
[ActionName("GetStaffsPaged")]
public IEnumerable<StaffsBasicInfo> GetStaffsPaged()
{
var take = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["take"]) ? 1000 : Convert.ToInt32(HttpContext.Current.Request.QueryString["take"]);
var skip = string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["skip"]) ? 1000 : Convert.ToInt32(HttpContext.Current.Request.QueryString["skip"]);
StaffsBasicInfoBL staffsBL = new StaffsBasicInfoBL();
List<StaffsBasicInfo> staffs = staffsBL.getAllStaffsBasicInfo();
staffs = staffs.Skip(skip).Take(take).ToList();
return staffs;
}
When I run my code, the Grid is always showing the first 10 records, but my database has 2000+ records.
I have tried lots of tutorials to solve this, but I cannot do pagination.
http://www.telerik.com/blogs/the-facts-on-using-kendo-ui-with-asp-net-webapi
According to the above tutorial, my code should work.
I have also tried this tutorial, but I Visual Studio cannot resolve the DataSource class.
http://blog.falafel.com/server-paging-sorting-filtering-kendo-datasourcerequest/
Please help me implement pagination

You are not returning "total" number of items present so that Kendo could generate total/size number of items in the pagination area.
Try returning
var totalCount = staffs.Count();
staffs = staffs.Skip(skip).Take(take).ToList();
return new { data = staffs, total = totalCount};
And in JavaScript, define schema (code removed for brevity):
$("#grid").kendoGrid({
// code removed for brevity
dataSource: {
transport: {
read: {
url: "/api/Users/GetStaffsPaged"
}
},
schema: {
data: "data",
total: "total"
}
}
});
Thus said, the approach here, which pulls all data from database and doing the pagination on server side, defeats the actual purpose of having server side pagination. Pagination should happen in database and not at server side.

Related

KendoUI grid for angularjs don't show data after data-binding

I attempt bind data to Kendo UI grid for AngularJS.
Folowing is asp.net mvc controller method:
public string GetCdcReport()
{
return
"[{\"ProductID\":1,\"ProductName\":\"Chai\",\"UnitPrice\":18,\"UnitsInStock\":39,\"Discontinued\":false}," +
"{\"ProductID\":2,\"ProductName\":\"Chang\",\"UnitPrice\":19,\"UnitsInStock\":17,\"Discontinued\":false}]";
}
AngularJs service method:
function getImportResultReport() {
return httpPost('getCdcReport');
}
Data-binding in angularjs controller:
vm.mainGridOptions = {
columns: [
{ field: "ProductID", title: "ID" },
{ field: "ProductName", title: "Product Name" },
{ command: [{ template: "<button class='k-button' ng-click='showDetails(dataItem)'>Show details</button>" }] },
],
pageable: true,
dataSource: {
pageSize: 5,
transport: {
read: function (e) {
dataservice.getImportResultReport().
then(function (data) {
e.success(data);
});
}
}
}
};
This code don't return error. Grid rendering 37 pages of 5 rows, but they is empty.
I think that grid must know what type of data set for binding. In my case it is jSon. How set json type for grid datasource? Or what is wrong if don't need to do this?

Kendo UI Grid with Drop down Template Not updating value after save to server

We are using a server based simple grid. The grid reads and updates data for a remote data source. It has two columns that are using drop down editors. Everything seems to work fine except that after saving, when editor closes, the changed values are not displayed in the edited row. It still shows the old value. When we try to refresh the grid using the sync event, it changes the order of the rows however, it does update the values on refresh.
It seems like the template function is not executed after the update is completed. How to edit the grid / code to ensure that the changed value is reflected in the grid?
Grid Definition code:
$("#servicetype-grid").kendoGrid({
pageable: true,
toolbar: [{name: "create", text: ""}, { template: kendo.template($("#servicetype-search-template").html())}],
columns: [
{
field: "serviceName", title: "Service Name"
},
{
field: "billCalculationTypeId",
editor: calculationTypeDropDownEditor,
template: function(dataItem) {
return kendo.htmlEncode(dataItem.billCalculationTypeName);
},
title: "Bill Calculation Type"
},
{
field: "payCalculationTypeId",
editor: calculationTypeDropDownEditor,
template: function(dataItem) {
return kendo.htmlEncode(dataItem.payCalculationTypeName);
},
title: "Pay Calculation Type"
},
{
command: [
{ name: "edit", text: { edit: "", cancel: "", update: "" }},
{ name: "destroy", text:""}
],
title: "Actions"
}
],
dataSource: dataSource,
sortable: {
mode: "single",
allowUnsort: false
},
dataBound: function(e) {
setToolTip();
},
edit: function(e) {
$('.k-grid-update').kendoTooltip({content: "Update"});
$('.k-grid-cancel').kendoTooltip({content: "Cancel"});
},
cancel: function(e) {
setToolTip();
},
editable: {
mode: "inline",
confirmation: "Are you sure that you want to delete this record?"
}
});
Drop down function is defined as:
function calculationTypeDropDownEditor(container, options) {
$('<input required data-text-field="name" data-value-field="id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: {
transport: {
read: {
dataType: "jsonp",
url: baseURL + "rips/services/calculationType/lookupList"
}
}
}
});
}
After doing some search on Google and browsing through different examples on Kendo site, I finally was able to resolve this issue. Following is my understanding of the problem and solution:
When we are using drop down box or combo box as a custom editor, generally we have a different datasource that contains a list options with an id and a value to show. I defined the template as "#=field.property#" of the field that I was looking up. In my case it was calculation type. Following is my model:
model: {
id: "serviceId",
fields: {
serviceName: { field:"serviceName", type: "string", validation: { required: { message: "Service Name is required"}} },
billCalculationType: { field: "billCalculationType", validation: { required: true}},
payCalculationType: { field: "payCalculationType", validation: { required: true} }
}
In above, billCalculationType and payCalculationType are supposed to be drop down list values displaying the calculation type name but storing the id of the corresponding calculation type. So, in my grid definition, I added following:
{ field: "billCalculationType",
editor: calculationTypeDropDownEditor,
template:"#=billCalculationType.name#",
title: "Bill Calculation Type" },
Where calculation dropdown editor is a function that builds a drop down from external data source. So, it works fine. However, for the template definition to work in (field.property) format, the server must return the value as a class for this field and not a simple text. So, in my server service, I returned in following format:
{"billCalculationType":{"id":"4028828542b66b3a0142b66b3b780001","name":"Hourly","requiredDetails":false},"payCalculationType":{"id":"4028828542b66b3a0142b66b3b960002","name":"Kilometers","requiredDetails":false},"serviceId":"4028828542b66b3a0142b66b3c16000a","serviceName":"XYZ"}
Notice that the billCalculationType and payCalculationType are returned as objects with name and id as properties. This allows the template to work properly.
Hope this helps.

Displaying grid data after switching to Server Side paging

I am converting my application to use Server Side Paging with the Kendo Grid UI. Prior to switching serverPaging to true, I was properly displaying my grid contents, and paging on the client side. However, once I turned on the serverPaging, my data was no longer visible. I have checked the network call, and my data is returning (only 2 records of 8 total) as expected, but I am not seeing it in the grid.
Here is the grid construction:
$v.KendoGrid.makeGrid(gridName, {
columns: [
{ field: 'IdentifierCode', title: 'User Name' },
{ field: 'CompanyName', title: 'Company' },
{ field: 'Email', title: 'Email' }
],
dataSource: {
pageSize: 2,
schema: {
data: 'Data', // records are returned in the data section of the response
model: {
id: 'Id',
fields: {
IdentifierCode: { type: 'string' },
CompanyName: { type: 'string' },
Email: { type: 'string' }
}
},
total: 'Total' // total number of records are in the total section of the response
},
serverPaging: true,
transport: {
read: {
url: window.urlConfigs.root + "Security/UserAccount/PagedListing"
dataType: "json",
type: "GET"
}
}
},
editable: false,
filterable: true,
height: 464,
pageable: true,
scrollable: true,
sortable: true
});
Here is the MVC Controller method:
public ActionResult PagedListing(int pageSize, int skip)
{
var entities = ReadRepo.All();
var total = entities.Count();
var data = entities.Skip(skip).Take(pageSize).Select(MapEntityToViewModel).ToList();
return Json(new { Total = total, Data = data }, JsonRequestBehavior.AllowGet);
}
And here is the data I get back on the network call:
{"Total":8,"Data":[{"Id":"928f0bb2-608b-417b-bf6e-e5c58f85fec2","IdentifierCode":"admin","FirstName":"Administrator","MiddleName":"of","MiddleNameHuman":"of","LastName":"GasStream","DisplayName":"Administrator of GasStream","Email":"admin#example.com","IsExternal":false,"UserTypeHuman":"Internal","CompanyId":"75bb05a4-1ec2-4042-aeba-a229008aca9f","CompanyName":"Entessa Pipeline & Terminal, MLP","CompanyIdentifierCode":"SHA","Password":"wFg/a/NEU6WM8z4YZBUduitIDROfeFz/+Za6leAHnBE=","PasswordChanged":false,"ForceNewPasswordFlag":false,"Settings":[],"RoleGroups":[]},{"Id":"47c29025-cfa8-4447-9ab7-a229008ad088","IdentifierCode":"contractcarl","FirstName":"Carl","MiddleName":null,"MiddleNameHuman":"","LastName":"Smithers","DisplayName":"Carl Smithers","Email":"carl#entessa.com","IsExternal":false,"UserTypeHuman":"Internal","CompanyId":"75bb05a4-1ec2-4042-aeba-a229008aca9f","CompanyName":"Entessa Pipeline & Terminal, MLP","CompanyIdentifierCode":"SHA","Password":"IWdH+qDIOucNrre6V4AgI6Exm2Vq5qkIdXdsWfP6jn4=","PasswordChanged":false,"ForceNewPasswordFlag":false,"Settings":[],"RoleGroups":[]}]}
I suspect I have missed something small, but after looking at this and trying all sorts of possible work-arounds, I cannot see it, so I am asking for some help. I thought once I got the data to return small sets from the Server, things would get simpler.
Thanks in advance,
Drew
I ended up finding the answer. the $v.KendoGrid was a method that wrapped the kendoGrid call itself, and in there something was getting reset to not allow the data to be parsed properly when it came back from the server properly paged.
I have since re-worked the mess so I can establish the necessary parameters in the $v.KendoGrid call for just my type of grid.
Thanks for the help, and the eyes to catch the comma, Brett.
Drew

ExtJS4 - Reconfiguring a grid in ASP.NET - JSON structure issue

One of ASP.NET's security features is proving to be a mountain to scale here - the "d" property addition when returning a JSON response appears to be confusing ExtJS when I attempt to reconfigure a gridpanel dynamically, causing it to fail when attempting to generate new column structure.
I followed this solution by nicholasnet:
http://www.sencha.com/forum/showthread.php?179861-Dynamic-grid-columns-store-fields
and it works beautifully, until the JSON payload is wrapped around the "d" property, e.g.
{"d":{
"metaData": {
"root": "data",
"fields": [{
"type": "int",
"name": "id",
"hidden": true,
"header": "id",
"groupable": false,
"dataIndex": "id"
}, ...omitted for brevity...]
},
"success": true,
"data": [{
"id": "1",
"controller": "Permissions",
"description": "Allow to see permission by roles",
"administrator": true,
"marketing": false
}]
}
}
I can't work out how to tell ExtJS to skirt around this problem. I've tried setting the "root" property of the AJAX reader to "d.data" but that results in the grid showing the correct number of rows but no data at all.
I've all the property descriptors required for column metadata ("name", "header", "dataIndex") in the JSON so I don't believe the JSON structure to be the cause. My main lead at the moment is that on the event handler:
store.on
({
'load' :
{
fn: function(store, records, success, operation, eOpts)
{
grid.reconfigure(store,store.proxy.reader.fields);
},
scope: this
}
}, this);
The fields in historyStore.proxy.reader.fields part is undefined when I pass the "d"-wrapped JSON. Anyone have any ideas on why this is or how to solve this issue?
edit: my Store/proxy
Ext.define('pr.store.Store-History', {
extend: 'Ext.data.Store',
model: 'pr.model.Model-History',
proxy: {
type: 'ajax',
url: '/data/history.json',
reader: {
type: 'json',
root: 'd'
}
}
});
Ext.define('pr.store.Store-History', {
extend: 'Ext.data.Store',
model: 'pr.model.Model-History',
proxy: {
type: 'ajax',
url: '/data/history.json',
reader: {
type: 'json',
root: 'data',
readRecords: function(data) {
//this has to be before the call to super because we use the meta data in the superclass readRecords
var rootNode = this.getRoot(data);
if (rootNode.metaData) {
this.onMetaChange(rootNode.metaData); // data used to update fields
}
/**
* #deprecated will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead
* #property {Object} jsonData
*/
this.jsonData = rootNode;
return this.callParent([rootNode]); // data used to get root element and then get data from it
},
}
}
});
Update:
you are not getting fields in reader because the default code for getting fields from data doesn't handle your wrapped data, so you need to change 'readRecords' function to handle your custom data

ComboBox not working in datagrid

I am missing something very basic, my comboxbox never appears, can somebody please look at the following code and tell me what I am missing, I have tried both .Select and ComboBox as type and I ma using dojo-1.5
var layout4 =
[
{ field: "abbr", name: "Abbreviation", width: 10 },
{ field: "name", name: "Name", width: 10 },
{ field: "capital", name: "Capital", width: '10'},
{ field: "combo", name: "combo", width: 10,
type: dojox.grid.cells.Select,
options: [ "new", "read", "replied" ],
editable:true
}
];
var store4 = { identifier: 'abbr',
label: 'name',
items: [
{ abbr:'ec', name:'Ecuador', capital:'Quito', combo:'' },
{ abbr:'eg', name:'Egypt', capital:'Cairo', combo:''},
{ abbr:'sv', name:'El Salvador', capital:'San Salvador', combo:''},
{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo', combo:''},
{ abbr:'er', name:'Eritrea', capital:'Asmara', combo:'' },
{ abbr:'ee', name:'Estonia', capital:'Tallinn', combo:''},
{ abbr:'et', name:'Ethiopia', capital:'Addis Ababa', combo:'' }
]};
storeData = new dojo.data.ItemFileReadStore(
{ data:store4}
);
// create a new grid:
var grid4 = new dojox.grid.DataGrid({
query: { abbr: '*' },
store: storeData,
clientSort: true,
rowSelector: '20px',
structure: layout4
}, document.createElement('div'));
// append the new grid to the div "gridContainer4":
dojo.byId("gridContainer4").appendChild(grid4.domNode);
// Call startup, in order to render the grid:
grid4.startup();
Try replacing the long line that you have using appendChild() with this one:
grid4.placeAt("gridContainer4");
Your code is rather scrambled and without seeing the whole thing it's a little hard to debug. Do you get any errors on the console? Can you post a complete example on JSFiddle?
The reason was that I was using ItemFileReadStore, and it was not allowed to edit an item in store and so combobox was not appearing. Using WriteStore solves this problem here. Ofcourse it was dumb to use readsotre.
Now I have a different problem where I want combobox to appear in grid where canEdit is implemented, but that is a different question.

Resources