Why sometimes kendo UI Grid can not show the data? - javascript

My problem is: when I change db.Contacts.Where( x => x.Id > 100).Select(...), The KendoUI Grid cannot show the data. However, when x=>x.Id < 100, it can show the data.
If I delete the Where(...), it also can not show the data.
What is the wrong? Thank you very much.
Here is my code.
public class HelloOneController : Controller
{
......
public JsonResult Contacts_Read()
{
var query = db.Contacts.Where(x => x.Id < 100 )
.Select(x => new
{
Id = x.Id,
Email = x.Email,
FirstName = x.FirstName,
LastName = x.LastName
}).ToList();
}
return Json(query, JsonRequestBehavior.AllowGet);
}
......
}
$("#grid").kendoGrid({
dataSource: {
transport: {
read: "/HelloOne/Contacts_Read",
dataType: "json"
},
schema: {
model:{
fields: {
Id: { type: "number" },
Email: { type: "string" },
FirstName: { type: "string" },
LastName: { type: "string" }
}
}
},
pageSize: 20
},
height: 500,
groupable: false,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [
{ title: "Id", field: "Id", width: 50 },
{ title: "Email", field: "Email" },
{ title: "First Name", field: "FirstName" },
{ title: "Last Name", field: "LastName" }
]
});

Related

Created item can not be edited or deleted without a grid refresh in ShieldUI

I want to use the ShieldUI library (grid component) in order to present tabular data to the user.
The issue with this library is that if I create a new item and right after I want to edit or delete it, the grid is unable to provide its id (as the database generates for me), although I return the id from backend after the INSERT query is executed. Here is what I tried:
<!-- HTML and JS part -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery Shield UI Demos</title>
<link id="themecss" rel="stylesheet" type="text/css" href="//www.shieldui.com/shared/components/latest/css/light/all.min.css" />
<script type="text/javascript" src="//www.shieldui.com/shared/components/latest/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="//www.shieldui.com/shared/components/latest/js/shieldui-all.min.js"></script>
</head>
<body class="theme-light">
<div id="grid"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#grid").shieldGrid({
dataSource: {
remote: {
read: "/products",
modify: {
create: {
url: "/products/productCreate",
type: "post",
data: function (edited) {
var date = edited[0].data.AddedOn ? edited[0].data.AddedOn.toJSON() : new Date().toJSON();
return {
Active: edited[0].data.Active,
AddedOn: date,
Category: edited[0].data.Category,
Name: edited[0].data.Name,
Price: edited[0].data.Price,
Id: edited[0].data.Id
};
}
},
update: {
url: "/products/productUpdate",
type: "post",
data: function (edited) {
var date = edited[0].data.AddedOn ? edited[0].data.AddedOn.toJSON() : new Date().toJSON();
return {
Active: edited[0].data.Active,
AddedOn: date,
Category: edited[0].data.Category,
Name: edited[0].data.Name,
Price: edited[0].data.Price,
Id: edited[0].data.Id
};
}
},
remove: {
url: "/products/productRemove",
type: "post",
data: function (removed) {
return { id: removed[0].data.Id };
}
}
}
},
schema: {
fields: {
Id: { path: "Id", type: Number },
Price: { path: "Price", type: Number },
Name: { path: "Name", type: String },
Category: { path: "Category", type: String },
AddedOn: { path: "AddedOn", type: Date },
Active: { path: "Active", type: Boolean }
}
}
},
rowHover: false,
columns: [
{ field: "Name", title: "Product Name", width: "300px" },
{ field: "Price", title: "Price", width: "100px" },
{ field: "Category", title: "Category", width: "200px" },
{ field: "AddedOn", title: "Added On", format: "{0:MM/dd/yyyy}" },
{ field: "Active", title: "Active" },
{
title: " ",
width: "100px",
buttons: [
{ cls: "deleteButton", commandName: "delete", caption: "<img src='/Content/img/grid/delete.png' /><span>Delete</span>" }
]
}
],
editing: {
enabled: true,
event: "click",
type: "cell",
confirmation: {
"delete": {
enabled: true,
template: function (item) {
return "Delete row with ID = " + item.Id
}
}
}
},
toolbar: [
{
buttons: [
{ commandName: "insert", caption: "Add Product" }
],
position: "top"
}
]
});
});
</script>
<style>
.deleteButton img
{
margin-right: 3px;
vertical-align: bottom;
}
</style>
</body>
</html>
Below is the ASP.MVC part:
[ActionName("productCreate")]
public Product PostProduct(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.Id = Products.Max(i => i.Id) + 1;
Products.Add(item);
return item;
}
To make this work, I need to refresh the grid's content by performing a sort operation (the framework updates the grid before sorting) or worse, a page refresh.
So what is the issue with this approach? Am I missing something?
We need to modify the create object and use AJAX call in order to make this work.
So instead of:
create: {
url: "/products/productCreate",
type: "post",
data: function (edited) {
var date = edited[0].data.AddedOn ? edited[0].data.AddedOn.toJSON() : new Date().toJSON();
return {
Active: edited[0].data.Active,
AddedOn: date,
Category: edited[0].data.Category,
Name: edited[0].data.Name,
Price: edited[0].data.Price,
Id: edited[0].data.Id
};
}
}
You have to do:
create: function (items, success, error) {
var newItem = items[0];
$.ajax({
type: "POST",
url: "/products/productCreate",
dataType: "json",
data: newItem.data,
complete: function (xhr) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
// update the id of the newly-created item with the
// one returned from the server
newItem.data.Id = xhr.responseJSON.Id;
success();
return;
}
}
error(xhr);
}
});
}

Kendo treelist Child node issue

whenever i cancelled the updating process from the child node,the child node just merge with root node,i don't find error in the console or i can't find anything suspicious.but after a reload,all becomes normal
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});
the updation and deletion works fine by the way,Here is the fiddle
https://jsfiddle.net/me09jLy7/2/
updation:
whenever i create a child to ranikannur gives me 3 children with same name in each root ranikannur,in my database there is only one child is parented by ranikannur but treelist shows it as 3 children in each parent node,the children count 3 is getting from the total ranikannurparent nodes(here tree has 3 ranikannur parent nodes)
i guess.how is this getting the 3 children?
u just try it...
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});

cannot display a table of data received from an ajax request in asp. net web api

I am trying to display a table of data returned by the following restful web api service accessible by this url. The problem is it displays only the header of the table and not the content.
/SMART/api/Build/GetAll
This url will return as output an IList of object called release, I have already tested this. The release object is structured as follows.
[Table("releases")]
public class Release
{
[Key]
public int Id { get; set; }
[StringLength(10)]
[Column("Name")]
public string Name { get; set; }
[StringLength(10)]
[Column("Type")]
public string Type { get; set; }
[Column("to_be_displayed")]
public bool ToBeDisplayed { get; set; }
}
Here is my javascript code
$.ajax({
type: 'GET',
url: '/SMART/api/Build/GetAll',
dataType: 'json',
contentType: "application/json",
success: function (data) {
alert(data);
// Get the JSON Data
var Data = new kendo.data.DataSource({
schema: {
model: {
id: "release.id",
fields: {
id: { type: "string" },
Name: { type: "string" },
Type : {type : "string"},
ToBeDisplayed: { type: "boolean" },
}
}
}
});
//Create a tab for the wip release
$('#listGrid').kendoGrid({
scrollable: false,
sortable: true,
resizable: true,
filterable: true,
autoSync: true,
dataSource: Data,
columns: [
{ field: "release.id", title: "Id" },
{ field: "release.Name", title: "Name" },
{ field: "release.ToBeDisplayed", title: "To be displayed", template: "<input name='ToBeDisplayed' type='checkbox' data-bind='checked: ToBeDisplayed' #= ToBeDisplayed ? checked='checked' : '' # class='build-tobedisplayed-checkbox'/>" },
]
});
}
});
Here is my cshtml code
<div id="listGrid" class="k-grid-content">
<div class="k-loading-mask" style="width:100%;height:100%"><span class="k-loading-text">Loading...</span><div class="k-loading-image"><div class="k-loading-color"></div></div></div>
</div>
Try the following Code:
function definitionUserGrid() {
var baseUrl = '/SMART/api/Build/GetAll';
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: baseUrl,
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: true,
pageSize: 15
});
$("#listGrid").kendoGrid({
dataSource: dataSource,
pageable: true,
reorderable: true,
resizable: true,
sortable: true,
filterable: {
mode: "row"
},
columns: [
{field: "Id",
title: "Id",
}, {
filterable: {
cell: {
enabled: true,
showOperators: false,
operator: "contains"
}
},
field: "Name",
title: "Name"
}, {
filterable: {
cell: {
enabled: true,
showOperators: false,
operator: "contains"
}
},
field: "ToBeDisplayed",
title: "To be displayed",
template: "<input name='ToBeDisplayed' type='checkbox' data-bind='checked: ToBeDisplayed' #= ToBeDisplayed ? checked='checked' : '' # class='build-tobedisplayed-checkbox'/>" },
}]
});
}
And finally:
call function definitionUserGrid()
$(function(){
definitionUserGrid();
});

How to do Creation Updation and Deletion of Data from IList for Kendo Grid?

this is my kendogrid code :
KendoDemosFactory.controller("MyCtrl", function ($scope, $sessionStorage) {
$scope.mainGridOptions = {
dataSource: {
transport: {
read: {url:"/User/GetUserDetail",datatype:"json"},
update: { url: "/User/UpdateUser", type: "POST" },
destroy:{ url:"/User/DeleteUser",type:"POST"},
Create:{url:"/User/CreateUser",type:"POST"}
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
},
batch: true,
pageSize: 5,
serverPaging: false,
serverSorting: false
},
sortable: true,
pageable: true,
navigatable: true,
toolbar: ["create", "save", "cancel"],
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [{
field: "FirstName",
title: "First Name",
width: "80px"
}, {
field: "LastName",
title: "Last Name",
width: "80px"
}, {
field: "Address",
width: "80px"
}, {
field: "Email",
width: "100px"
}, {
field: "Gender",
width: "80px"
},
{
field: "Salary",
width:"100px"
},
{ command: "destroy", title: " ", width: 100 }
],
editable:true
};
})
and here is my controller with my userlist and all the methods :
public ActionResult GetUserDetail()
{
IList<UserModel> userList = new List<UserModel>()
{
new UserModel{
id=1,
FirstName = "Pawan",
LastName = "Kapoor",
Address = "Mohali",
Email = "test#test.com",
Gender = "Male",
Salary = 25000
},
new UserModel
{
id=2,
FirstName = "Ayan",
LastName = "Banerjee",
Address = "Bangalore",
Email = "test1#test.com",
Gender = "Male",
Salary = 30000
},
}
}
[HttpPost]
public ActionResult CreateUser()
{
IList<UserModel> userList = new List<UserModel>();
return Json(userList, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult UpdateUser()
{
IList<UserModel> userList = new List<UserModel>();
return Json(userList, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult DeleteUser()
{
IList<UserModel> userList = new List<UserModel>();
return Json(userList, JsonRequestBehavior.AllowGet);
}
My kendo Grid is populating fine with editable functionality and all the CRUD controls but i am not able to bind data with the controller using CRUD Methods(they are not getting hit and any crud functionality is not getting persisted). Please help
Let me give you a few notes to correct your your code.
If you do not want to make batch update, send to controller only the current row.
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: options.models[0] };
}
}
Correct your update action method as follows: MVC will bind the data send from grid into UserModel.
[HttpPost]
public ActionResult UpdateUser(UserModel model)
{
// do something with model
return Json(model, JsonRequestBehavior.AllowGet);
}
This link will lead you to solve your problem

Can we filter the data from exact data not from filtered data?

In my project had a kendo grid with filtering, filtering is working fine,but data is not clearing dynamically while filter is cleared. filter data is cleared by button click how to clear without "clear" button click.My grid code is
var grid = $("#grid").kendoGrid({
dataSource: {
type : "odata",
transport : {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders"
},
schema : {
model: {
fields: {
OrderID : { type: "number" },
Freight : { type: "number" },
ShipName : { type: "string" },
OrderDate: { type: "date" },
ShipCity : { type: "string" }
}
}
},
pageSize : 10
},
filterable: true,
sortable : true,
pageable : true,
columns : [
{
field : "OrderID",
filterable: false
},
"Freight",
{
field : "OrderDate",
title : "Order Date",
width : 100,
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipName",
title: "Ship Name",
width: 200
},
{
field: "ShipCity",
title: "Ship City"
}
]
}).data("kendoGrid");
The only thing I can think of is to use the parameterMap function (when type is 'read') to get rid of the filters that you do not need and always send only the last item of filters array.

Categories