Record doesn't show in grid of Kendo UI MVC - model-view-controller

I use this code for grid Kendo UI, But it doesn't show data in the grid. I trace code, it's right, only doesn't show record in grid. I don't know how to solve this problem.
public JsonResult GridData()
{
var products = new List<Product>();
for (var i = 1; i <= 100; i++)
{
products.Add(new Product { Id = i, Name = "Product " + i });
}
return Json(products, JsonRequestBehavior.AllowGet);
}
public class Product
{
public int Id { set; get; }
public string Name { set; get; }
}
<link href="~/Content/kendo/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.common.core.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.default.min.css" rel="stylesheet" />
<script src="~/Scripts/kendo/jquery.min.js"></script>
<script src="~/Scripts/kendo/kendo.web.min.js"></script>
<script src="~/Scripts/kendo/kendo.all.min.js"></script>
<div id="report-grid"></div>
<script type="text/javascript">
$(function () {
var productsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Home/GridData/',
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'GET'
},
parameterMap: function (options) {
return kendo.stringify(options);
}
},
schema: {
data: "Data",
total: "Total",
model: {
fields: {
"Id": { type: "number" }, //تعیین نوع فیلد برای جستجوی پویا مهم است
"Name": { type: "string" },
"IsAvailable": { type: "boolean" },
"Price": { type: "number" }
}
}
},
error: function (e) {
alert(e.errorThrown.stack);
},
pageSize: 5,
sort: { field: "Id", dir: "desc" },
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
$("#report-grid").kendoGrid({
dataSource: productsDataSource,
autoBind: true,
scrollable: false,
pageable: true,
sortable: true,
filterable: true,
reorderable: true,
columnMenu: true,
columns: [
{ field: "Id", title: "شماره", width: "130px" },
{ field: "Name", title: "نام محصول" },
{
field: "IsAvailable", title: "موجود است",
template: '<input type="checkbox" #= IsAvailable ? checked="checked" : "" # disabled="disabled" ></input>'
},
{ field: "Price", title: "قیمت", format: "{0:c}" }
]
});
});
</script>

Please try with the below code snippet.
<script type="text/javascript">
$(function () {
var productsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Home/GridData',
dataType: "json"
},
parameterMap: function (options) {
return kendo.stringify(options);
}
},
schema: {
model: {
fields: {
"Id": { type: "number" },
"Name": { type: "string" }
}
}
},
error: function (e) {
alert(e.errorThrown.stack);
},
pageSize: 5,
sort: { field: "Id", dir: "desc" },
//serverPaging: true,
//serverFiltering: true,
//serverSorting: true
});
$("#report-grid").kendoGrid({
dataSource: productsDataSource,
autoBind: true,
scrollable: false,
pageable: true,
sortable: true,
filterable: true,
reorderable: true,
columnMenu: true,
columns: [
{ field: "Id", title: "شماره", width: "130px" },
{ field: "Name", title: "نام محصول" }
]
});
});
</script>
Let me know if any concern.

Related

KendoUI populate dropdown

I am new to kendoUI and I need some assistance with getting the data that is returned from a function to populate into the dropdown. I am currently getting [object HTMLSelectElement] - you can see in the image attached. Any help is appreciated.
data is returned in function
dropdown is not showing the years returned
LoadAcceptedSubmissionsGrid: function (module) {
// Grid for "Accepted" tab
var isAccepted = "true";
gridAcceptedSubmissions = $("#gridAcceptedSubmissions").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
serverSorting: true,
serverFiltering: true,
allowUnsort: true,
transport: {
read: function (options) {
var strFilter = JSON.stringify(options.data.filter);
var strSort = JSON.stringify(options.data.sort);
var pageSize = options.data.pageSize === undefined && gridAcceptedSubmissions !== null ?
gridAcceptedSubmissions.dataSource.total() :
options.data.pageSize;
var acceptedSubmissionsUrl = commonUrl + "/Forms/Submissions/"
+ upacsSessionId + "/" + userId + "/" + form + "/" + isAccepted + "/"
+ options.data.page + "/" + pageSize + "/" + options.data.skip;
$.ajax({
type: "POST",
url: acceptedSubmissionsUrl,
xhrFields: {
withCredentials: true
},
data: {
filter: strFilter,
sort: strSort
},
success: function (response) {
options.success(response);
},
error: function (result) {
options.error(result);
}
});
}
},
pageSize: 10,
batch: false,
schema: {
total: function (response) {
return response.total;
},
data: function (response) {
return response.values;
},
model: {
id: "submissionId",
fields: {
state: { editable: false, type: "string", sort: "asc" },
fipsCode: { editable: false, type: "number", sort: "asc" },
year: { editable: false, type: "number", sort: "desc" },
name: { editable: false, type: "string" },
createdBy: { editable: false, type: "string" },
createdOn: { editable: false, type: "date" },
lastModifiedBy: { editable: false, type: "string" },
lastModifiedOn: { editable: false, type: "date" },
isEditable: { editable: false, type: "boolean" },
isReviewable: { editable: false, type: "boolean" }
}
}
}
},
groupable: false,
sortable: {
showIndexes: true,
mode: "multiple"
},
resizable: true,
selectable: "row",
scrollable: true,
filterable: true,
navigatable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 10
},
dataBound: this.GridDataBound,
columns: [
{
field: "submissionId",
title: "Id",
},
{
field: "state",
title: "State",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("state", "name", true)
},
sort: "ascending"
},
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("year", null, true)
},
sort: "descending"
},
{
field: "status",
title: "Status",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("status", null, true)
}
},
{
field: "createdBy",
title: "Initiated By",
filterable: {
ui: this.FormCreatedByAcceptedFilter
}
},
{
field: "createdOn",
title: "Initiated On",
format: "{0:g}",
},
{
field: "lastModifiedBy",
title: "Modified By",
filterable: {
ui: this.FormLastModifiedByAcceptedFilter
}
},
{
field: "lastModifiedOn",
title: "Modified On",
format: "{0:g}"
},
{
title: "Action",
headerTemplate: "<div class='headerTemplate'><span class='headerText'>Action</span>" +
"<button class='clearAllFilters' id='clearAllFiltersAcceptedSubmissions' tabindex=0> Clear All Filters</button></div>",
command: [
{
name: "View",
text: " ",
visible: function (dataItem) { return !dataItem.isEditable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-View' title='View Form' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-eye'><span class='sr-only'>View form</span></i></a>";
return tmpl;
},
click: function (e) {
e.preventDefault();
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-existing-form", module);
}
},
{
name: "View History",
text: " ",
visible: function (dataItem) { return !dataItem.isReviewable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-ViewHistory' title='View Form History' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-history'><span class='sr-only'>View form history</span></i></a> ";
return tmpl;
},
click: function (e) {
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-status-history", module);
}
}
],
},
]
}).data("kendoGrid");
gridAcceptedSubmissions.hideColumn(0);
$("#clearAllFiltersAcceptedSubmissions").click(function () {
gridAcceptedSubmissions.dataSource.filter({});
});
},
Without seeing what BuildMultiCheckboxDataSource is doing, I can only make assumptions.
However, since you have declared year as an IEnumerable<int> then the datasource does not need to be anything elaborate. Simply set it to the collection being returned by the server:
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/my-endpoint-to-fetch-years-here"
}
}
})
},
sort: "descending"
}

How to restrict the check box check to 5 in Kendo UI grid

How to restrict the check box check to 5 in Kendo UI grid.
I am using Kendo UI grid with check box. I want to restrict check box selection to 5
Please find the code attached
$(function () {
$("#grid").kendoGrid({
dataSource: {
pageSize: 10,
transport: {
read: {
url: "url",
dataType: "json"
}
},
schema: {
model: {
id: "Id",
fields: {
Id: {
type: "string"
},
Title: {
type: "string"
},
OrderDate: {
type: "date",
defaultValue: null
}
}
}
}
},
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "Title", title: "Title" },
{ field: "OrderDate", title: "Order Date", format: "{0:MM/dd/yyyy}", encoded: true }
]
});
});
function onChange(arg) {
//console.log("The selected product ids are: [" + this.selectedKeyNames().join(", ") + "]");
}
Thanks in advance
This is tested code according your requirement only difference is that checkbox column created with template.
Reference link : https://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Selection/grid-selection-checkbox
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.mobile.all.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.1.115/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<button id="showSelection">Show selected IDs</button>
<script>
$(document).ready(function () {
//DataSource definition
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
editable: false,
nullable: true
},
ProductName: {
validation: {
required: true
}
},
UnitPrice: {
type: "number",
validation: {
required: true,
min: 1
}
},
Discontinued: {
type: "boolean"
},
UnitsInStock: {
type: "number",
validation: {
min: 0,
required: true
}
}
}
}
}
});
//Grid definition
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
//define dataBound event handler
dataBound: onDataBound,
toolbar: ["create"],
columns: [
//define template column with checkbox and attach click event handler
{ template: "<input type='checkbox' class='checkbox' />" },
"ProductName", {
field: "UnitPrice",
title: "Unit Price",
format: "{0:c}",
width: "100px"
}, {
field: "UnitsInStock",
title: "Units In Stock",
width: "100px"
}, {
field: "Discontinued",
width: "100px"
}, {
command: ["edit", "destroy"],
title: " ",
width: "172px"
}
],
editable: "inline"
}).data("kendoGrid");
//bind click event to the checkbox
grid.table.on("click", ".checkbox" , selectRow);
$("#showSelection").bind("click", function () {
var checked = [];
for(var i in checkedIds){
if(checkedIds[i]){
checked.push(i);
}
}
alert(checked);
});
});
var checkedIds = {};
//on click of the checkbox:
function selectRow() {
//// *********Prevent to select more than 5 record*************************
if(Object.keys(checkedIds).length>=5)
{
this.checked=false;
}
/// **********************************
var checked = this.checked,
row = $(this).closest("tr"),
grid = $("#grid").data("kendoGrid"),
dataItem = grid.dataItem(row);
checkedIds[dataItem.id] = checked;
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
//on dataBound event restore previous selected rows:
function onDataBound(e) {
var view = this.dataSource.view();
for(var i = 0; i < view.length;i++){
if(checkedIds[view[i].id]){
this.tbody.find("tr[data-uid='" + view[i].uid + "']")
.addClass("k-state-selected")
.find(".checkbox")
.attr("checked","checked");
}
}
}
</script>
</body>
</html>
Let me know if you have questions or concerns.

How I write a dynamic URL in kendo UI DataSource like "update/{id}"

I have a web API. In that I wrote a update method. But it need to id of the table row to update to the row.
I use a grid to show data and use a toolbar to edit the row.
My question is how I pass that id to the update.
Can someone guide me ??
update: function(options) {
$.ajax( {
url: function(data) { return "updateUsuarios/"+data.Id,
dataType: "json",
.....
Well i suggest you, explain more your question, but i think this examples could help , if you have a toolbar as a template like this:
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<button type="button" id="update">Update</button>
</div>
</script>
You "grid" need the attr "toolbar"
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
filterable:true,
toolbar: kendo.template($("#template").html()),
columns: [
{ field:"username", title: "Username" , width: "120px" },
{ field: "nombre", title:"Nombre", width: "120px" },
{ field: "apellido", title:"Apellido", width: "120px" },
{ field: "ci", title:"Documento de Identidad", width: "120px" },
{ field: "email", title:"Direccion de Correo", width: "120px" },
{ field: "activo",title:"Estatus", width: "120px" },
{ field: "fecha_caducidad",title:"Fin Demo", width: "120px",template: "#= kendo.toString(kendo.parseDate(fecha_caducidad, 'yyyy-MM-dd'), 'MM/dd/yyyy') #" },
{ field: "licencia_status",title:" ", width: "40px",template:'<img src="assets/images/#:data.licencia_status#.png"/>' },
{ command: ["edit"], title: " ", width: "120px" }],
editable: "popup",
dataBound: function () {
var rows = this.items();
$(rows).each(function () {
var index = $(this).index() + 1;
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
},
selectable: true
});
So,you can configure a kendo button and add functionality in the event click:
$("#update").kendoButton({
click: function(){
//Here you will have the selected row
var self=$('#grid').data('kendoGrid')
var index = self.items().index(self.select());
var rowActual= self.dataSource.data()[index];
rowActual=self.dataItem(self.select());
if(rowActual==undefined || rowActual ==null) {
alert("No row selected");
}else{
$.ajax({
type: "POST",
url: "update",
data: {
id:rowActual.id
},
dataType: 'json',
success: function (data) {
},
error: function(){
}
});
}
}
});
and send in the ajax the row id, but if you are update the row with the inline edition you could try with a datasource like this
dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: "readUsuarios",
dataType: "json",
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
$.ajax( {
url: "updateUsuarios",
dataType: "json",
data: {
models: kendo.stringify(options.data.models)
},
success: function(data) {
// response server;
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "id",
fields: {
username: { editable: false, nullable: true },
nombre: { validation: { required: true } },
apellido: { type: "string", validation: { required: true} },
ci: { type: "string", validation: { required: true} },
email: { type: "string", validation: { required: true } },
activo: { type: "boolean",editable: false },
fecha_caducidad: { type: "date" },
licencia_status:{editable: false}
}
}
}
});
I hope this help!

How to get field type in Kendoui?

Is there any method like that dataSource.getFieldType(field) in datasource:
var dataSource = new kendo.data.DataSource({
// somethings here,
schema : {
model : {
post_id : {type: "number" },
post_title : {type:"string"},
post_date : {type:"date"}
}
}
});
var fieldType = dataSource.getFieldType("post_title"); // it should return string
You should define a getFieldType function as:
function getFieldType(dataSource, field) {
return dataSource.options.schema.model.fields[field].type;
}
and using it would be:
var fieldType = getFieldType(dataSource, "post_title");
Alternatively, you can extend KendoUI DataSource for defining a new method called getFieldType by doing:
kendo.data.DataSource.prototype.getFieldType = function(field) {
return this.options.schema.model.fields[field].type;
}
and using it would be:
var fieldType = dataSource.getFieldType("post_title");
Check here the version using DataSource extension:
$(document).ready(function() {
kendo.data.DataSource.prototype.getFieldType = function(field) {
return this.options.schema.model.fields[field].type;
}
$("#show").on("click", function() {
var ds = $("#grid").data("kendoGrid").dataSource;
alert("Freight: " + ds.getFieldType("Freight"));
});
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 550,
pageable: true,
columns: [
{
field:"OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShipCity",
title: "Ship City"
}
]
});
});
html {
font-size: 12px;
font-family: Arial, Helvetica, sans-serif;
}
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1316/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1316/js/kendo.all.min.js"></script>
<button id="show" class="k-button">Show Freight type</button>
<div id="grid"></div>

Filter dirty rows in kendo grid

I have a kendo grid connected to a rather large table via odata. I use batch editing. I need to be able to filter all rows that have changes on them so the user can review those changes before they commit the changes to the db. Any idea how could I do that? Thanks
Do you need to show also deleted records (not sync'ed)? Otherwise you can set a filter with the condition:
{
field: "dirty",
operator: "equals",
value: true
}
Something like:
grid.dataSource.filter({
field: "dirty",
operator: "equals",
value: true
});
$(document).ready(function () {
var crudServiceBaseUrl = "http://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 550,
toolbar: [
"create",
"save",
"cancel"
],
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}" },
{ field: "UnitsInStock", title: "Units In Stock" },
{ field: "Discontinued" },
{ command: "destroy", title: " " }],
editable: true
}).data("kendoGrid");
$("#dirty").on("click", function(e) {
console.log("dirty", grid.dataSource.data());
grid.dataSource.filter({
field: "dirty",
operator: "equals",
value: true
});
e.preventDefault();
});
$("#all").on("click", function(e) {
grid.dataSource.filter({});
e.preventDefault();
});
});
html {
font-size: 12px;
font-family: Arial, Helvetica, sans-serif;
}
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1119/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1119/js/kendo.all.min.js"></script>
<button id="dirty" class="k-button">Dirty</button>
<button id="all" class="k-button">All</button>
<div id="grid"></div>

Resources