I would like to use the Kendo grid with remote data virtualization. I also need to have a custom method for the transport.read property.
My grid is configured like this:
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
serverPaging: true,
serverSorting: true,
pageSize: 100,
transport: {
read: function (options) {
// Get the template items, which could be products, collections, blogs or articles
getTemplateItems().then(function (data) {
options.success(data);
});
}
}
},
schema: {
total: function(response) {
return 2000;
}
},
height: 543,
scrollable: {
virtual: true
},
sortable: true,
columns: [
{ field: "title", title: "Title" }
]
});
});
function getTemplateItems() {
var deferred = $q.defer();
smartseoEntityMapping.getEntityInfo({ mappedEntityType: mappedEntityType.Product }).$promise.then(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
The problem is that the read method is only called once when the grid is initialized. It is not called when the scroll reaches the last item in the current visible set.
I suspect that the grid needs the total number of items but I cannot understand how to set the total number of items. Setting a method for the schema.total property does not work because the method is never called.
So I would like to ask you, is this scenario possible at all, to have the virtualization work with a custom transport.read method, which needs to be called every time to get the next page of data?
Why I am using a custom read? Well I cannot just set an url for the transport.read property because my remote call is made via an angularjs resource, involves setting authentication, etc...
schema is a property of a kendo datasource. It looks like you have it outside of the datasource.
Should be:
$("#grid").kendoGrid({
dataSource: {
serverPaging: true,
serverSorting: true,
pageSize: 100,
transport: {
read: function (options) {
// Get the template items, which could be products, collections, blogs or articles
getTemplateItems().then(function (data) {
options.success(data);
});
}
},
schema: {
total: function(response) {
return 2000;
}
}
},
height: 543,
scrollable: {
virtual: true
},
sortable: true,
columns: [
{ field: "title", title: "Title" }
]
});
Related
I have kendo dropdownlist on page which is fetching results from database as below. I also have a grid at the same page at same time which needs kendo dropdownlist value i.e the value from years dropdownlist but I am unable to get it at the same time.This is how I am following. Where I am doing wrong.
<script type="text/javascript">
var GridUrl;
$("#Years").kendoDropDownList({
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
transport: {
read: {
dataType: "json",
url: "../../Service/GetYears"
}
}
}
});
$(document).ready(function () {
BindGridData();
GridUrl = '#Url.Action("Read", "Home")';
});
function BindGridData()
{
GridDataSource = new kendo.data.DataSource({
type: "aspnetmvc-ajax",
serverFiltering: true,
serverPaging: true,
serverSorting: true,
pageSize: 10,
transport: {
read: {
url: GridUrl,
data: { year: $('#Years').val() }
}
},
schema: {
data: "Data", total: "Total"
}
});
}
Changing line to this
year: $('#Years').data("kendoDropDownList").value()
should do a trick. You need to get instance of kendoDropDownListwidget in order to get its value. You need to do so, because kendoDropDownListwidget value is not saved directly into html element
First of all, you need to move the initialisation of the kendoDropDownList inside the document ready function. If you don't you may end up refering to elements that are not loaded (yet).
The second change that should be done is how you get the value from the kendoDropDownList. Usually, you should refer to the widget instead of the DOM element: $('#Years').data("kendoDropDownList").value()
Finally, you didn't mention how and when your grid was binded but you may want to refresh the grid data if the user change the dropdown value. If it's the case, you may want to use change event of the dropdown to refresh the grid data.
$(document).ready(function () {
$("#Years").kendoDropDownList({
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
transport: {
read: {
dataType: "json",
url: "../../Service/GetYears"
}
}
},
change: function(e) {
$("#YourGrid").data("kendoGrid").dataSource.read();
}
});
BindGridData();
GridUrl = '#Url.Action("Read", "Home")';
});
function BindGridData() {
GridDataSource = new kendo.data.DataSource({
type: "aspnetmvc-ajax",
serverFiltering: true,
serverPaging: true,
serverSorting: true,
pageSize: 10,
transport: {
read: {
url: GridUrl,
data: { year: $('#Years').data("kendoDropDownList").value() }
}
},
schema: {
data: "Data", total: "Total"
}
});
}
I'm quite new using kendo grids.
So far I've managed to do a few stuff and got a workaround for all my problems.
I have a grid with 2 columns.
One column is a product code that the user should enter, and the other is product quantity that should be filled automatically after the user enter the product code. This should be done on change event.
The product quantity is obtained by a service.
So far I have the following code:
var dataSource = new kendo.data.DataSource({
batch: false,
autoSync: false,
data: [],
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductCode: { type: "string", validation: { required: true } },
ProductQuantity: { type: "number", validation: { required: false, editable: false } }
}
}
},
edit: function (e) {
if (e.model.isNew() == false) {
$('[name="ProductQuantity"]').attr("readonly", true);
}
},
change: function (e) {
if (e.action == "itemchange") {
debugger;
apModel.getProductQuantities(e.items[0].ProductCode).ifFetched().then(function (data) {
var data = JSON.parse(data.Response);
})
//how to access next cell???
$("#ap-grid").data("kendoGrid").saveRow();
}
}
});
$("#ap-grid").kendoGrid({
dataSource: dataSource,
pageable: false,
height: 550,
toolbar: ["create"],
columns: [
{ field: "ProductCode", title: "Product Code" },
{ field: "ProductQuantity", title: "Quantity" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "inline",
});
I can't find a way how to access the next cell to add the data to it.
Can you give me a hint?
thanks in advance,
André
When you set e.items[0].ProductQuantity in OnChange event handler grid cell should automatically update value if datasource bind correctly.
According to kendo docs:
e.items - The array of data items that were affected (or read).
That means it reference at original row of datasource.
My grid won't call my parameterized DataSourceResult methods. It just calls the parameterless one. I've studied this article till my eyes are falling out. What am I missing?
From my javascript controller:
$("#grid").kendoGrid({
dataSource: {
transport: {
read: function (options) {
userService.getGridUserList($.extend(options.data))
.success(function (result) { options.success(result); })
.error(function (result) { options.error(result); });
},
parameterMap: function(options, type) {
return kendo.stringify(options);
}
},
requestStart: function (e) {
},
requestEnd: function (e) {
},
schema: {
data: "data",
total: "total"
},
pageSize: 25,
serverPaging: true,
serverSorting: true,
serverFiltering: true
},
height: 600,
filterable: true,
sortable: true,
pageable: true,
columns: [
{ field: "firstName", title: "First Name" },
{ field: "lastName", title: "Last Name" },
{ field: "email", title: "email" }
]
});
From my C# WebAPI:
//**doesn't get called**
public DataSourceResult GetGridUserList(GetUserGridListInput input)
{
var q = repository.GetAll().OrderBy(t => t.Id);
return q.ToDataSourceResult(input.Take, input.Skip. input.Sort, input.Filter);
}
//**doesn't get called**
public DataSourceResult GetGridUserList(int take, int skip, IEnumerable<Sort> sort, Filter filter)
{
var q = repository.GetAll().OrderBy(t => t.Id);
return q.ToDataSourceResult(take, skip, sort, filter);
}
//**gets called every time**
public DataSourceResult GetGridUserList()
{
var q = repository.GetAll().OrderBy(t => t.Id);
return q.ToDataSourceResult(500, 0, null, null);
}
Turns out I was clobbering the grid parameters in my service call. What I needed to fix it, is to add {} as the first parameter:
userService.getGridUserList({}, $.extend(options.data))
The example uses a POST request, perhaps the grid requires that.
"I'm using a POST since MVC blocks unsecured GETS by default. That's
good since we're going to be needing a POST request structure coming
up shortly."
I cannot get Kendo Grid to populate from server side data.
I have a grid builder function as as follows:
var build = function (carrier, date) {
var urlBase = 'my base url';
var datasource = new kendo.data.DataSource({
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
schema: {
model: {
id: 'Id',
fields: {
StatementDate: { type: "string", editable: false },
CobDate: { type: "string", editable: false },
//lots more fields
Status: { type: "string", editable: false },
Matched: { type: "boolean", editable: true }
}
}
},
transport: {
read: function (options) {
var address = urlBase + '/' + carrier + '/' + date;
$.ajax({
url: address,
type: "POST",
data: JSON.stringify(options.data),
contentType: "application/json",
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
},
//update function omitted
parameterMap: function (data, operation) {
if (operation == "read") {
return JSON.stringify(data)
}
},
change: function (e) {
var data = this.data();
console.log(data.length); // displays "77"
}
}
});
return datasource;
};
return {
build: build
}
Grid Definition
elem.kendoGrid({
columns: [
{ field: "StatementDate", title: "State Date", width: 125 },
{ field: "CobDate", title: "COB Date", width: 100 },
//lots more fields
{ command: ["edit"], title: " ", width: "85px"}],
resizable: true,
sortable: true,
editable: "inline",
columnMenu: true,
filterable: true,
reorderable: true,
pageable: true,
selectable: "multiple",
change: this.onSelectedRecordChanged,
toolbar: kendo.template($('#' + templateName).html()),
scrollable: {
virtual: true
},
height: 800
});
I trigger the update via a button click. When I look at the response I see the data. Looks good but the grid will not show the data. It has previously worked fine when data was completely client side.
If I break point on the AJAX call back. I see the correct results.
The grid is bound with data bind. The datasource is a property on a viewmodel.
<div id="grid" data-bind="source: dataSource"></div>
At the start of the app. I create view model
var viewModel= kendo.observable(new GridViewModel(...
and bind
kendo.bind($('#grid'), viewModel);
If I look at the datasource attached to the grid, I see data for the page as expected
This has previously worked fine when data was client side.
I have tried using read() on datasource, and refresh() method on grid. Neither seems to work.
Example response content from server
{"Data":[{"Id": //lots more fields, 20 records],"Total":90375,"AggregateResults":null,"Errors":null}
Any help very much appreciated.
I found the cause in datasource schema missing
{ data: 'Data', total: 'Total' }
I am trying to implement server side sorting with kendo grid in my MVC application. but sorting option is not showing. i have double checked that i have enabled all the necessary option (made the serversorting to true to the the kendo grid data source and made the scrollable to true to the grid element) to do this but still i am able to find the sortable option. below is my kendo grid code
Kendo Grid Script
var grid = $("#grid");
grid.children().remove();
grid.kendoGrid({
columns: [{attributes:"",field:"",template:"${ResultFields[0].Value},title:"Column 1",width:"110px"},{attributes:"",field:"",template:"${ResultFields[1].Value},title:"Column 1",width:"110px"}],
resizable: true,
reorderable: true,
scrollable: true,
filterable: true,
columnMenu: true,
selectable: "row",
selectable: "multiple",
dataBound: function () { alert("Data Bound"); },
dataSource: {
transport: {
read: {
url: '#Url.Action("Index", "KendoServerSideSorting")',
type: "GET",
dataType: "json",
traditional: true,
data: {
itemTypeId: 1,
where: values,
orderBy: ["", "", ""],
},
},
},
schema: {
data: "Items",
total: "TotalItems",
},
serverPaging: true,
pageSize: 10,
error: function (e) {
alert(e.errors);
}
},
pageable: {
pageSize: 10,
input: true,
pageSizes: [10, 20, 30, 50, 100, 250],
},
change: function () { alert("Change event"); },
})
Controller Action will look like this
public JsonResult Search(int itemTypeId, int skip, int take, string[] where, string[] orderBy)
{
var v = Kernel.Get<IItemSearch>().Search(itemTypeId, skip, take, where, orderBy);
return Json(v, JsonRequestBehavior.AllowGet);
}
*Can anyone help me to resolve this issue. *
You can use the helper functionality from KendoGridBinderEx to parse all the commands (like filter and sort) and do the filtering and sorting at the server-side automatically using DynamicLinq.
See this project : https://github.com/StefH/KendoGridBinderEx for some examples.Also available as NuGet package : https://www.nuget.org/packages/KendoGridBinderEx/