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?
Related
now,I'm try to use bootstrapTable to load my data that using ASP.NET WebMethod.
$.ajax(): url is set like this: "url:mydata.aspx/GetData"
and this is work fine.
in the other way:
$('#mytab').bootstrapTable({
method: 'post',
contentType: "application/x-www-form-urlencoded",
url:"mydata.aspx/GetData",
toolbar: '#toolbar',
striped: true,
dataField: "res",
pageNumber: 1,
pagination:true,
queryParamsType:'limit',
queryParams:queryParams,
sidePagination:'server',
pageSize:10,
pageList:[5,10,20,30],
showRefresh:true,
showColumns:true,
clickToSelect: true,
toolbarAlign:'right',
buttonsAlign:'right',
toolbar:'#toolbar',
columns:[
{
title:'全选',
field:'select',
checkbox:true,
width:25,
align:'center',
valign:'middle'
},
{
title:'ID',
field:'ID',
visible:false
},
{
title:'登录名',
field:'LoginName',
sortable:true
},
{
title:'姓名',
field:'Name',
sortable:true
},
{
title:'手机号',
field:'Tel',
},
{
title:'邮箱',
field:'Email'
},
{
title:'注册日期',
field:'CreateTime',
sortable:true
},
{
title:'状态',
field:'Attribute',
align:'center',
formatter:operateFormatter
}
],
responseHandler:function(res){
return res;
},
onLoadError: function(status){
alert("error"+status);
}
})
function operateFormatter(value,row,index){
。。。
}
function queryParams(params){
return{
pageSize: params.limit,
pageIndex:params.pageNumber,
content:$('#search_name').val()
}
}
ASP.NET API code here
[WebMethod]
public static string GetData(int pageSize, int pageIndex, string content)
{
return "{total:200,rows:[{......}]}";
}
But now I got an error code:
[error200]has been alerted.
I want to know [onLoadError]'s error status's map
200:XXXX
400:XXXX
500:XXXX
bootstrapTable document has no error status map information.
please help........
Paste your JSON data into myjson.com and really make sure it's good json (without errors). Then post a JSFiddle with a subset of your code and using the url from the myjson.com link it provides.
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.
I want to bind a KendoGrid to an object array so that it reflects what ever the user enters. The object will have two fields ExceptionName and ExceptionType. ExceptionType needs to be a dropdown of 5 items (this is working). The ExceptionName will be free text.
If I double click on the kendo grid, I can edit, but it does not reflects in the object. Same thing for Delete & new row. (So I think I am doing something wrong in the binding or in the declaration of the object)
Below, find a snippet of my code:
Object array:
var authorizationInformation = [{
id:1,
exemptionName: "",
exemptionType: "Unknown"
}];
KendoGrid:
$("#AuthorizationGrid").kendoGrid({
columns: [{
field: "exemptionName", title: "Exemption Name"
},
{
field: "exemptionType",
title: "Exemption Type",
template: function (value) {
for (var i = 0; i < exemptionTypeList.length; i++) {
if (exemptionTypeList[i].exemptionType == value.exemptionType) {
return exemptionTypeList[i].description;
}
}
},
editor: function (container) {
var input = $('<input id="exemptionType" name="exemptionType">');
input.appendTo(container);
// initialize a dropdownlist
input.kendoDropDownList({
dataTextField: "description",
dataValueField: "exemptionType",
dataSource: exemptionTypeList
}).appendTo(container);
}
},
{
command: "destroy"
}],
dataSource: authorizationInformation,
editable: true,
scrollable: false,
});
Any suggestion would be appreciated.
Thanks, M
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.
I am trying Kendo UI out and I am using the examples provided for studying purpose. Let's suppose I am using a large data source of several hundreds of thousand elements. If I'm using paging and the page size is 10, I would really like to be able to get only 10 elements from the web-page and if Kendo UI was able to know that in reality the number of elements is much bigger, but we are showing only 10.
This is what I currently have:
var initGrid = true;
var grid2Data;
function getDataSource()
{
return grid2Data.Data;
}
var grid;
function getPageIndex()
{
if (!(grid)) {
return 0;
}
return grid.pager.page() - 1;
}
function getPageSize() {
if (!(grid)) {
return 10;
}
return grid.pager.pageSize();
}
function getFilters() {
if (!(grid)) {
return "";
}
return grid.dataSource.filter();
}
function getSorts() {
if (!(grid)) {
return "";
}
return grid.dataSource.sort();
}
function getParams() {
return getPageSize();
}
function postTest() {
if (initGrid) {
$.post('myurl' + getParams(), function (data) {
grid2Data = data;
$("#grid").kendoGrid({
dataBound: onDataBound,
dataSource: {
data: getDataSource(),
schema: {
model: {
fields: {
Email: { type: "string" },
FullName: { type: "string" },
LogCreateDate: { type: "date" },
RoleName: { type: "string" },
UserName: { type: "string" }
}
}
},
pageSize: 10
},
height: 300,
scrollable: false,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
{
field: "Email",
title: "Email",
width: 100
},
{
field: "FullName",
title: "Full Name",
width: 100
},
{
field: "LogCreateDate",
title: "Created",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
},
{
field: "RoleName",
title: "Role",
width: 50
},
{
field: "UserName",
width: 100
}
]
});
grid = $("#grid").data("kendoGrid");
});
}
else {
}
initGrid = false;
}
$(document).ready(function () {
postTest();
});
My problem is that the grid is showing that this is element 1-10 from 10 and it's the first page. I would like the grid to show me a page index and item count given by me. How can I set the number of elements and the page index of the grid? Is this possible? Thanks.
When you choose serverPaging in the DataSource by setting it to true. You receiver in the server information about the page number (page), the page size (pageSize), number of records to skip (skip)... (look for serverPaging in http://docs.kendoui.com/api/framework/datasource) and in exchange you should return not only the array with the data of that page but also the total number of rows. Then you implement in schema.total the function for accessing the number of records. I.e. Lets assume that you return as result the following object:
{
rows: [
{ id: 1, col1: "col1.1", col2: "col1.2" },
{ id: 2, col1: "col2.1", col2: "col2.2" },
{ id: 3, col1: "col3.1", col2: "col3.2" }
],
totalRows : 1000
}
Then you might implement schema.total as:
schema: {
total: function (response) {
return response.totalRows;
}
}
Where response is the object received from the server.
NOTE: Actually in this case would be enough defining the schema as:
schema: {
total: "totalRows";
}
}
Since total is directly stored in totalRows field.
Check http://demos.kendoui.com/web/grid/remote-data.html for an example.