Kendo grid footer template sum issue - jquery-ui

var dataSourceDashboard = new kendo.data.DataSource({
pageSize: 20,
type: "json",
transport: {
read: function (operation) {
if (navigator.onLine) {
$.ajax({
url: '/Home/Dashboard_Read/',
type: "GET",
dataType: "json",
success: function (response) {
try
{
localStorage.setItem("Dashboard_Read", JSON.stringify(response));
}
catch (domException)
{
if (domException.name === 'QuotaExceededError' ||
domException.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
// Fallback code comes here.
$("#progressMsgError").html("Cannot save the data for offline use, please clear the cache, or call administrator!");
$('#myModalError').modal('show');
}
}
operation.success(response);
BindSitesCombo(response);
//// initial sync of data
//var cashedDataBaseJson = [];
//var cashedDataBase = localStorage.getItem("cashedDataBase");
//if (cashedDataBase != null || cashedDataBase != undefined) {
// cashedDataBaseJson = JSON.parse(cashedDataBase);
// if (cashedDataBaseJson.length > 0) {
// syncInitialData(cashedDataBaseJson);
// localStorage.setItem("cashedDataBase", JSON.stringify(cashedDataBaseJson));
// }
//}
//else
//{
// syncInitialData(response);
// localStorage.setItem("cashedDataBase", JSON.stringify(response));
//}
var cashedDataBase = localStorage.getItem("cashedDataBase");
if (cashedDataBase == null || cashedDataBase == undefined) {
localStorage.setItem("cashedDataBase", JSON.stringify(response));
}
else {
var cashedDataBaseJson = [];
var cashedDataBase = localStorage.getItem("cashedDataBase");
if (cashedDataBase != null || cashedDataBase != undefined) {
cashedDataBaseJson = JSON.parse(cashedDataBase);
var i = response.length;
while (i--)
{
var ifsiteisinthelist = contains(cashedDataBaseJson, response[i]);
if (ifsiteisinthelist == false)
{
cashedDataBaseJson.push(response[i]);
}
}
localStorage.setItem("cashedDataBase", JSON.stringify(cashedDataBaseJson));
}
}
rempvesyncedlinks();
},
error: function (response)
{
window.location.href = "/account/login";
}
});
}
else {
var cashedData = localStorage.getItem("Dashboard_Read");
if (cashedData != null || cashedData != undefined) {
//if local data exists load from it
var data = JSON.parse(cashedData);
operation.success(data);
BindSitesCombo(data);
rempvesyncedlinks();
}
}
}
},
schema: {
model: {
id: "SiteID",
}
},
//change: function (e) {
// $.each(dataSourceDashboard.data(), function (index, value) {
// $('#cmbAllSites')
// .append($("<option></option>")
// .attr("value", value.SiteID)
// .text(value.SiteName));
// });
//}
change: function (e) {
rempvesyncedlinks();
},
aggregate: [
{ field: "DailyTotalFormated", aggregate: "sum" },
{ field: "WeeklyTotalFormated", aggregate: "sum" },
{ field: "WeeklySiteTotalFormated", aggregate: "sum" },
{ field: "WeeklyGoal", aggregate: "sum" }
],
});
$(function () {
$("#gridDashboard").kendoGrid({
dataSource: dataSourceDashboard,
filterable: false,
groupable: false,
toolbar: false,
pageable: {
change: function (e) {
rempvesyncedlinks();
}
},
sortable: true,
height: 600,
columns: [
{ field: "SiteName", title: "MY COMPANIES", template: '#=SiteName#',footerTemplate: "Total " },
{ field: "DailyTotalFormated", title: "MY DAILY TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklyTotalFormated", title: "MY WEEKLY TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklySiteTotalFormated", title: "WEEKLY SITE TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklyGoal", title: "WEEKLY SITE GOAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "", title: "SYNC", template: "# if (isSynced == true) { #" +
"<div style='width: 130px;margin: auto;'><img src='/images/ready.png' alt='Up-to-date' /><div style='font-size:15px; font-weight:bolder; float: right;'>Ready</div></div>" +
"# } else { #" +
"<div style='width: 130px;margin: auto;'><img src='/images/pleasesync.png' alt='Up-to-date' /><div style='font-size:15px; font-weight:bolder; float: right;'>Please Sync</div></div>" +
"# } # <a id='syncforoffline#=SiteID#' href='##' onclick='syncDataForSite(#=SiteID#);return false;'>Sync for offline</a>"
},
{ field: "SiteLogo", title: " ", hidden : true },
],
editable: false
});
$("#cmbAllSites").change(function ()
{
var di = dataSourceDashboard.data()[this.selectedIndex - 1];
setSiteID(di.SiteID, di.SiteLogo, di.SiteName);
});
});
Footer sum is not calculated
What is wrong in this code, why does the total show last row by default?

I fixed the issue. I am just adding:
model: {
id: "SiteID",
fields: {
SiteName: { type: "string" },
DailyTotalFormated: { type: "number" },
WeeklyTotalFormated: { type: "number" },
WeeklySiteTotalFormated: { type: "number" },
WeeklyGoal: { type: "number" }
}
}

Related

How can I get the selected checkbox in kendo grid?

I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "Descripción" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.

How to access Customer table's data in nopcommerce

I want to show Customer table's data of nopcommerce in admin page.
i did write a plugin for that and receive data in controller but in view i have a problem and show me error happened message.
here is my controller code:
public class UserDetailsController : BasePluginController
{
private ICustomerService _UserDetail;
public UserDetailsController(ICustomerService UserDetail)
{
_UserDetail = UserDetail;
}
public ActionResult Manage()
{
return View();
}
[HttpPost]
public ActionResult GetUsers(DataSourceRequest userDetail)
{
var details = _UserDetail.GetAllCustomers();
var gridModel = new DataSourceResult
{
Data = details,
Total = details.Count
};
return Json(gridModel);
}
}
And this is my view code:
#{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<script>
$(document).ready(function() {
$("#user-details").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetUsers", "UserDetails"))",
type: "POST",
dataType: "json",
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
}
},
requestEnd: function(e) {
if (e.type == "update") {
this.read();
}
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info:false
},
editable: {
confirmation: true,
mode: "inline"
},
scrollable: false,
columns: [
{
field: "Email",
title: "User Name",
width: 200
},
{
command: [
{
name: "edit",
text: "#T("Admin.Common.Edit")"
}, {
name: "destroy",
text: "#T("Admin.Common.Delete")"
}
],
width: 200
}
]
});
});
</script>
<div id="user-details"></div>
can anybody help me?
Change your GetUsers method on this way:
var details = _UserDetail.GetAllCustomers();
var gridModel = new DataSourceResult
{
Data=details.Select(x=>
{
return new UserDetail()
{
Email= x.Email
};
}),
Total = details.Count(),
};
return Json(gridModel);

Kendo MVC Grid paging buttons not changing results displayed

I have a Kendo Grid. The paging numbers are ok, items per page is ok, but when I press on page number the results in grid isn't changing, all results are shown in first page. Please help here.
Below is my code:
<script>
$(function() {
$("#invoices-grid").kendoGrid({
dataSource: {
data: #Html.Raw(JsonConvert.SerializeObject(Model.Invoices)),
schema: {
model: {
fields: {
JobNumber: { type: "string" },
CustomerName: { type: "string" },
DepartmentName: { type: "string" },
DateInvoice: { type: "string" },
ValidDays: { type: "number" },
Delivery: { type: "string" },
IsPayed: { type: "boolean" },
Payed: { type: "number" },
Status: { type: "boolean" },
}
}
},
#*type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("List", "Finances"))",
type: "POST",
dataType: "json",
data: additionalData1
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},*#
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
columns: [
{
field: "JobNumber",
title: "#T("gp.Invoice.Fields.JobNumber")",
template: '#= JobNumber #'
},
{
field: "CustomerName",
title: "#T("gp.Invoice.Fields.CustomerName")",
template: '#= CustomerName #'
},
{
field: "DepartmentName",
title: "#T("gp.Invoice.Fields.DepartmentName")",
template: '#= DepartmentName #'
},
{
field: "DateInvoice",
title: "#T("gp.Invoice.Fields.DateInvoice")",
template: '#= DateInvoice #'
},
{
field: "ValidDays",
title: "#T("gp.Invoice.Fields.ValidDays")",
template: '#= ValidDays #'
},
{
field: "Delivery",
title: "#T("gp.Invoice.Fields.Delivery")",
template: '#= Delivery #'
},
{
field: "Payed",
title: "#T("gp.Invoice.Fields.IsPayed")",
template: '#= (Payed == 2) ? "Комп." : ((Payed == 1) ? "ДЕ" : "НЕ") #'
},
{
field: "Id",
title: "#T("Common.Edit")",
width: 100,
template: '#T("Common.Edit")'
},
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "popup"
},
scrollable: false,
selectable: true,
change: function(e) {
var selectedRows = this.select();
var jobId = parseInt($(selectedRows).data('job-id'));
var jobItemId = parseInt($(selectedRows).data('job-item-id'));
var result = $.get("#Url.Action("SideDetails", "Production")/" + jobItemId);
result.done(function(data) {
if (data) {
$(".job-edit .jobItemDetails").html(data);
}
});
},
rowTemplate: kendo.template($("#invoiceRowTemplate").html()),
});
});
</script>
protected virtual void PrepareInvoiceFinanceListModel(FinanceListModel model,FormCollection form/*,string SearchJobItemNumber*/)
{
var customers = model.SearchCustomerId;
var isChecked = model.IsChecked;
var searchString = model.SearchJobItemNumber;
var IsChecked1 = model.IsChecked1;
// searchString = model.SearchJobItemNumber;/* "001/2016";*/
//var searchString = model.SearchJobItemNumber;
//searchString = "091/2016";
if (model == null)
throw new ArgumentNullException("model");
var finishedJobs = _jobService.GetJobsByHasInvoice(false);
finishedJobs = finishedJobs.OrderByDescending(x =>
{
var firstOrDefault = x.JobItems.FirstOrDefault();
return firstOrDefault?.DateCompletition ?? new DateTime();
}).ToList();
foreach (var job in finishedJobs)
{
var jobModel = job.ToModel();
model.FinishedJobs.Add(jobModel);
}
var jobsBycustomers = finishedJobs.GroupBy(x => new { x.CustomerId, x.Customer.Name }).Select(x => new JobCustomersModel()
{
CustomerId = x.Key.CustomerId,
CustomerName = x.Key.Name,
JobsCount = x.Count(),
});
model.FinishedJobStatus = new JobStatusesModel()
{
Status = _localizationService.GetResource("gp.jobs.whitout.invoice"),
Value = (int)JobStatusEnum.Finished,
Count = finishedJobs.Count,
CustomersJobs = jobsBycustomers.ToList()
};
var invoices = _invoiceService.GetAllInvoices(searchString, isChecked, IsChecked1, customers);
foreach (var invoice in invoices)
{
var inv = invoice.ToModel();
// var a = invoice.Payed;
model.Invoices.Add(inv);
}
///////////////////// ////////////////////////
//var allCustomers = _invoiceService.GetAllCustomers(customers);
//foreach (var customer in allCustomers)
//{
// var cust = customer.ToModel();
// model.SearchCustomerId = customer.CustomerId;
// model.Invoices.Add(cust);
//}
var invoiceByCustomer = invoices
.GroupBy(x => new { x.CustomerId, x.CustomerName })
.Select(x => new JobCustomersModel()
{
CustomerId = x.Key.CustomerId,
CustomerName = x.Key.CustomerName,
JobsCount = x.Count(),
});
model.InvoiceStatus = new JobStatusesModel()
{
Status = _localizationService.GetResource("gp.jobs.with.invoice"),
Value = (int)JobStatusEnum.Finished,
Count = invoices.Count,
CustomersJobs = invoiceByCustomer.ToList()
};
var latestOffers = _offerService.GetLatestOffers(0, 10);
foreach (var offer in latestOffers)
{
var offerModel = offer.ToModel();
model.LatestOffers.Add(offerModel);
}
}
Currently server operations are enabled...
serverPaging: true,
serverFiltering: true,
serverSorting: true
... but the transport configuration is commented out. This is the cause of the problem.
If you want to use server operations, then configure the dataSource transport. Otherwise, use local data binding and disable server operations, as in this example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.default.min.css">
<script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>
</head>
<body>
<div id="invoices-grid"></div>
<script>
$(function() {
var d = [];
for (var i = 1; i <= 100; i++) {
d.push({Id: i, CustomerName: "CustomerName " + i});
}
$("#invoices-grid").kendoGrid({
dataSource: {
data: d,
schema: {
model: {
id: "Id",
fields: {
CustomerName: { type: "string" }
}
}
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
//serverPaging: true,
//serverFiltering: true,
//serverSorting: true
},
columns: [
{
field: "CustomerName",
title: "gp.Invoice.Fields.CustomerName",
template: '#= CustomerName #'
},
{
field: "Id",
title: "Common.Edit",
width: 100,
template: 'Common.Edit'
},
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "popup"
},
scrollable: false,
selectable: true,
change: function(e) {
}
});
});
</script>
</body>
</html>

Kendo UI Treelist rows disappears after editing

I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = #Html.Raw(#ViewBag.XmlData); //jsonarray data
$( document ).ready(function() {
});
function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
{
var divMessage = $('#toggler');
if(divMessage.css('display') != 'none')
{
divMessage.clearQueue();
divMessage.stop();
divMessage.css('display','none');
}
if (timeout == 0)
divMessage.text(message).toggle('slow');
else
divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');
}
var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
transport: {
read: function(e) {
e.success(parsedXmlDataInJson);
},
update: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
value = updatedItem;
return false;
}
});
e.success();
},
create: function(e) {//Works for root element when editing only once - it's broke my treelist.
e.data.Id = GetId();
parsedXmlDataInJson.push(e.data);
e.success(e.data);
},
destroy: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
parsedXmlDataInJson.splice(indx, 1);
}
});
e.success();
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: false,
schema: {
model: {
id: "Id",
parentId: "parentId",
fields: {
Id: {
type: "number",
editable: true,
nullable: false
},
parentId: {
field: "parentId",
nullable: true
}
}
}
}
});
$("#treeList").kendoTreeList({
resizable: true,
dataSource: treelistds,
toolbar: ["create"],
columns: [{
field: "typeAndAttributes",
width:400
}, {
field: "text",
title: "Текст",
}, {
field: "cData",
title: "CDATA",
}, { //my custom command
command: ["edit", "destroy", "createchild", {
name: "commentOut",
text: "commentOut",
click: function(e) {
var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command
dataItem.commentedOut = !dataItem.commentedOut;
var isCommentedOut = dataItem.commentedOut;
var childNotes = this.dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) //
{
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
//обновляем цвет и текст кнопок у всех элементов вызывая dataBound
$("#treeList").data("kendoTreeList").refresh();
},
}, ]
}],
messages: {
commands: {
edit: "Изменить",
destroy: "Удалить",
createchild: "Добавить"
}
},
dataBound: function(e) {
this.autoFitColumn(3);
Databound(e.sender, e.sender.table.find("tr"));
},
editable: true,
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html()),
window: {
width:800
}
},
edit: function(e) { //invokes when popup open
$("#date").kendoDateTimePicker({
});
$("#cDataEditor").kendoEditor({
tools: [
"formatting", "bold", "italic", "underline", "insertUnorderedList",
"insertOrderedList", "indent", "outdent", "createLink", "unlink"
],
resizable: {
content: true,
toolbar: true,
max:350
}
});
//my custom logic. Popup contains many fileds splitted from one model field
if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
var fileds = e.model.typeAndAttributes.split(';').
filter(function(v) {
return v !== ''
});
e.container.find("#type").val(fileds[0]);
var length = fileds.length;
for (i = 1; i < length; i++) {
var keyAndValue = fileds[i].split('=');
if (keyAndValue[0] != "id")
e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
else
e.container.find("#xmlId").val(keyAndValue[1].trim());
}
}
},
save: function(e) { //invokes when saving
var splitter = "; ";
var inputValue = $("input[id='type']").val().trim();
if (e.model.type !== undefined) {
e.model.typeAndAttributes = e.model.type;
} else {
e.model.typeAndAttributes = inputValue;
}
var allInputs = $(":input[data-appointment=attributes]");
allInputs.each(function(index, input) { //collect inputs in one filed
var attrName;
var attrValue;
if (input.id != "id") {
attrName = input.id;
e.model[attrName];
} else {
attrName = "id";
attrValue = e.model["xmlId"];
}
//значение изменили и оно не пустое
if (attrValue !== undefined && attrValue !== "") {
if (attrValue == false)
return true;
e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
}
//my custom logic
else if (input.value.trim() && input.value != "on") {
e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
}
})
}
});
//рекурсивно помечаем ряды как закомментированные или нет
function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) {
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
}
//Раскрашивает строки соответственно значению закомментировано или нет
function Databound(sender, rows) {
rows.each(function(idx, row) {
var dataItem = sender.dataItem(row);
if (dataItem.commentedOut) {
//обозначаем ряд как закомментированный
$(row).css("background", "#DCFFE0");
$(row).find("[data-command='commentout']").html("Раскомментировать");
} else {
//обозначаем ряд как незакомментированный
$(row).css("background", "");
$(row).find("[data-command='commentout']").html("Закомментировать");
}
})
}
});
var currentId = 0;
function GetId() { //генерирование Id для новых записей
var dataSource = $("#treeList").data("kendoTreeList").dataSource;
do {
currentId++;
var dataItem = dataSource.get(currentId);
} while (dataItem !== undefined)
return currentId;
}

Bind results from search

I cannot bind results from search in kendo grid. I've tried many times, I'm in trouble four days, I don't know what is wrong here,
When i debug action everything is working perfect,data is OK, return grid result are OK, but results aren't shown in kendo.
Here is my code:
<script>
$(function() {
$("a.k-button").on('click', function (e) {
debugger;
e.preventDefault();
var dataObj = serializeByFieldsWrap(".invoiceForm");
var dataUrl = $(this).data('url');
// dataObj.ToolboxId = toolboxId;
$('body').css('cursor', 'wait');
var result = $.ajax({
type: "POST",
url: dataUrl,
dataType: 'json',
data: dataObj,
//complete: $("#invoices-grid").data("kendoGrid").data.read(),
});
result.done(function (data) {
console.log(data);
var grid = $('#invoices-grid').data("kendoGrid");
grid.dataSource.data(data);
});
result.fail(function (error) {
console.log(error);
});
});
});
</script>
Controller:
public ActionResult List(DataSourceRequest command, FinanceListModel model)
{
var searchString = model.SearchJobItemNumber;
var isChecked = model.IsChecked;
var invoices = _invoiceService.GetAllInvoices(searchString, isChecked);
var gridModel = new DataSourceResult
{
Data = invoices.Select(x => {
var jobModel = x.ToModel();
return jobModel;
}),
Total = invoices.TotalCount
};
return Json(gridModel, "application/json", JsonRequestBehavior.AllowGet);
}
Kendo UI Grid:
<script>
$(function() {
$("#invoices-grid").kendoGrid({
dataSource: {
data: #Html.Raw(JsonConvert.SerializeObject(Model.Invoices)),
schema: {
model: {
fields: {
JobNumber: { type: "string" },
CustomerName: { type: "string" },
DepartmentName: { type: "string" },
DateInvoice: { type: "string" },
ValidDays: { type: "number" },
Delivery: { type: "string" },
IsPayed: { type: "boolean" },
Payed: { type: "number" },
Status: { type: "boolean" },
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: function () {
var row = this.element.find('tbody tr:first');
this.select(row);
},
columns: [
#*{
field: "Status",
title: "#T("gp.Jobs.Fields.Status")",
template: '#= Status #'
},*#
{
field: "JobNumber",
title: "#T("gp.Invoice.Fields.JobNumber")",
template: '#= JobNumber #'
},
{
field: "CustomerName",
title: "#T("gp.Invoice.Fields.CustomerName")",
template: '#= CustomerName #'
},
{
field: "DepartmentName",
title: "#T("gp.Invoice.Fields.DepartmentName")",
template: '#= DepartmentName #'
},
{
field: "DateInvoice",
title: "#T("gp.Invoice.Fields.DateInvoice")",
template: '#= DateInvoice #'
},
{
field: "ValidDays",
title: "#T("gp.Invoice.Fields.ValidDays")",
template: '#= ValidDays #'
},
{
field: "Delivery",
title: "#T("gp.Invoice.Fields.Delivery")",
template: '#= Delivery #'
},
{
field: "Payed",
title: "#T("gp.Invoice.Fields.IsPayed")",
template: '#= (Payed == 2) ? "Комп." : ((Payed == 1) ? "ДЕ" : "НЕ") #'
},
{
field: "Id",
title: "#T("Common.Edit")",
width: 100,
template: '#T("Common.Edit")'
}
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "popup"
},
scrollable: false,
selectable: true,
change: function(e) {
var selectedRows = this.select();
var jobId = parseInt($(selectedRows).data('job-id'));
var jobItemId = parseInt($(selectedRows).data('job-item-id'));
var result = $.get("#Url.Action("SideDetails", "Production")/" + jobItemId);
result.done(function(data) {
if (data) {
$(".job-edit .jobItemDetails").html(data);
}
});
},
rowTemplate: kendo.template($("#invoiceRowTemplate").html()),
});
});
</script>
DataSourceResult formats your server response like this:
{
Data: [ {JobNumber: "...", FieldName: "bar", ... } ],
Total: 100
}
In other words, the data items array is assigned to a Data field, and the total items count is assigned to a Total field. The Kendo UI DataSource configuration must take this into account by setting schema.data and schema.total:
http://docs.telerik.com/kendo-ui/framework/datasource/crud#schema
http://docs.telerik.com/kendo-ui/framework/datasource/crud#read-remote
schema: {
data: "Data",
total: "Total"
}

Resources