I am developing a web application which deals with interactive grids. I am using Kendo UI for displaying grids and doing CRUD operations. I am new to Kendo UI. We are performing database calls using jquery, Ajax only. I was able to make it read the data from the database and display it. But I am stuck at CRUD operations. How to get the event that a specific row or a specific single data is changed and perform the update. Please help me to understand how to do the crud operations. I couldn't find it in detail anywhere. There are 8 parameters which are in the first column. The user should be able to change the rest of the data except the parameters.
following is the code for Grid. CreateWBDGridData triggers the database service call and creates the table. gridSource is JSON data getting from the database after converting through Json convert function.
$(document).ready(function()
{
var param ="HOLE_DIAMETER|4.875_CASING_ID|5.5_GRAVEL_PACK|NET_PERF_THICKNESS|PERF_DIAMETER|PERF_GRAVEL_PERM_#19k|GRAVEL_BETA_FACTOR_#19K|SHOT_DENSITY";
$.when(GetWBDGridDataByWell(param)).then(function (data) {
});
});
function CreateWBDGridData(gridSource) {
if (gridSource == undefined) return;
console.log(gridSource);
$("#grid").kendoGrid({
dataSource: {
data: gridSource,
schema: {
model: {
fields: {
ParameterName: { type: "string" },
Zone_1: { type: "number" },
Zone_2: { type: "number" },
Zone_3: { type: "number" },
}
}
},
// pageSize: 20
},
//height: 550,
//scrollable: true,
//sortable: true,
//filterable: true,
//reorderable: true,
resizable:true,
//pageable: {
// input: true,
//numeric: false
//},
columns: [
{ field: "ParameterName", title: "Lucius 01", width: 300 },
{ field: "Zone_1", title: "Zone 1", width: 100 },
{ field: "Zone_2", title: "Zone 2", width: 100 },
{ field: "Zone_3", title: "Zone 3", width: 100 },
]
});
}
Controller
var dspstore = "System.Sources.Db.MsSql.DSPStore";
function GetWBDGridData(queryName, param) {
var varData = CreateParamQuery(dspstore, queryName, param);
CallService(GetWBDGridDataCompleted, varData);
}
var GetWBDGridDataCompleted = function (result) {
if (varDataType == "json") {
var myItems = $.parseJSON(result.GetDataItemsResult);
CreateWBDGridData(myItems);
}
}
Service call
function CallService(ServiceCompleted, varData) {
$.support.cors = true;
$.ajax({
context: this,
disableCaching: false,
headers: {
"Access-Control-Allow-Origin": '*',
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: varType, //GET or POST or PUT or DELETE verb
url: varUrl, // Location of the service
data: varData, //Data sent to server
//contentType: varContentType, // content type sent to server
dataType: varDataType, //Expected data format from server
processdata: varProcessData, //True or False
success: function (msg) {//On Successfull service call
ServiceCompleted(msg);
},
error: ServiceFailed// When Service call fails
});
}
Ok, as I Understand there 8 parameters which are the first column, have had has 3 more items which user can edit if so do as below.
$("#grid").kendoGrid({
dataSource: {
transport: {
read: function (options) {
$.ajax({
url: "/Your Controller/your read Action",
dataType: "json",
cache: false,
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
},
update: function (options) {
$.ajax({
url: "/Your Controller/your Update Action",
dataType: "json",
cache: false,
data:{model:options.data.models},
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
fields: {
ParameterName: { type: "string",editable: false },
Zone_1: { type: "number",editable: true, validation: { required: true } },
Zone_2: { type: "number",editable: true, validation: { required: true } },
Zone_3: { type: "number" ,editable: true, validation: { required: true }},
}
}
},
pageSize: 10
},
resizable:true,
columns: [
{ field: "ParameterName", title: "Lucius 01", width: 300 },
{ field: "Zone_1", title: "Zone 1", width: 100 },
{ field: "Zone_2", title: "Zone 2", width: 100 },
{ field: "Zone_3", title: "Zone 3", width: 100 },
]
});
}
Use the model to specify the editable and non-editable fields and Your Data Source Data parameter does not use unless you're doing local calls, to do server calls call it as a function as shown above.
and your Controller action should look like below : (I Assume your using MVC)
[HttpGet]
public ActionResult ReadGridJson()
{
return Json(yourlist, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult UpdateGridJson(YourModelType model)
{
//update the DB and return the updated item
return Json(updateItem, JsonRequestBehavior.AllowGet);
}
Hope this helps, For more info check out the API DOC http://docs.telerik.com/kendo-ui/api/web/grid
Related
I define a grid in my page :
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/Grid/GetPerson",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'Get'
},
update: {
url: function (person) {
debugger;
return "/Grid/Update";
},
contentType: 'application/json; charset=utf-8',
type: "POST",
},
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: "ID",
fields: {
ID: { type: "number", editable: false, nullable: true },
Name: { validation: { required: true } },
Family: { validation: { required: true, min: 1 } },
Tel: {}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
toolbar: ["create"],
columns: [
{ field: "Name", title: "نام" },
{ field: "Family", title: "فامیل" },
{ field: "Tel", title: "تلفن", width: "100px" },
{ command: [{ name: "edit", text: "ویرایش" }, { name: "destroy", text: "حذف" }], title: "عملیات", width: "160px" }],
messages: {
editable: {
cancelDelete: "لغو",
confirmation: "آیا مایل به حذف این رکورد هستید؟",
confirmDelete: "حذف"
},
commands: {
create: "افزودن ردیف جدید",
cancel: "لغو کلیهی تغییرات",
save: "ذخیرهی تمامی تغییرات",
destroy: "حذف",
edit: "ویرایش",
update: "ثبت",
canceledit: "لغو"
}
},
editable: "popup"
});
});
In person parameter in update function, i can access changed row by :
person.models[0]
it gives me :
Object {ID:1,Name:"pejman",Family:"kam",Tel:"098787887"}
SO i want to send this data to the server, so i have a action in GridController:
[HttpPost]
public void Update(TblPerson person)
{
//do update
}
for doing it, i try :
url: function (person) {
return "/Grid/Update/" + JSON.stringify(person.models[0])
},
in the update method, but it doesn't work, how can i do it?
NOTE: when i using above in Network tab of browser give me Bad Reuest error:
URL:http://localhost:2145/Grid/Update/%7B%22ID%22:1,%22Name%22:%22pejman%22,%22Family%22:%22kam%22,%22Tel%22:%22098787878%22%7D
Status Code:400 Bad Request
The problem is that kendo.stringify(options.models) sends your object in JSON string. So I believe that your js code can stay as it is. Just change your Update method in controller to something like:
[HttpPost]
public void Update(string models)
{
var values = JsonConvert.DeserializeObject<IEnumerable<TblPerson>>(models);
foreach (var value in values)
{
//Your action
}
}
The approach above just assume that you can send more models to update. Don't forget using Newtonsoft.Json
Here is my grid:
$("#category-gridview").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: function (options) {
return '/Product/GetCategories?id=' + $("#selectedProductId").val() + '&company=' + $("#company-dropdown").val() + '&language=' + $("#country-dropdown").val();
},
dataType: "json",
type: "POST"
},
destroy: {
url: '/Product/DeleteProductCategory',
dataType: "json",
type: "POST",
contentType: "application/json"
},
parameterMap: function (options, operation) {
console.log("HÄÄR");
console.log(options);
if (operation !== "read" && options.models) {
return JSON.stringify({
category: options
});
}
}
},
schema: {
model: {
fields: {
id: {
type: "string"
},
name: {
type: "string"
},
}
}
},
},
columns: [{
field: "id",
hidden: true
}, {
field: "name",
title: "Category",
width: "30px"
}, {
command: "destroy",
title: " ",
width: 15
}],
editable: false,
});
somehow the read function works as expected but when i press the delete button i won't even reach my parameter map function.
When i look in chrome console there is no request sent to my controller.
here is my controller method:
[HttpPost]
public JsonResult DeleteProductCategory(CategoryResponse category)
{
return Json(category);
}
Let me try to answer, but to note that i change your transport and the column setting to match the field using kendo because obviously i can't use yours. Similar to this
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/products",
dataType: "jsonp"
},
destroy: {
url: "http://demos.telerik.com/kendo-ui/service/products/destroy",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
At first glance i notice you use "POST" on read and delete call, actually you don't need them?
But then you said that you couldn't reach the parametermap, i came to
think of
You set editable : false, how can you edit it if you
set it to false? you should make it to editable : true(note: also you can try to set it to false and then you can see the delete function will not work)
DEMO
Instead of stringifing {param:value} Simply stringify value i.e stringify(options.models) for parameter category
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return { category: kendo.stringify(options.models) };
}
}
Here i my c sharp code of controller api class DefComapny whose value are always null while posting a data from kendo grid thats why not entering any thing to database?
[HttpPost]
public void SaveDefCompny()
{
var result = new List<DefCompany>();
using (var data = new RPDBEntities())
{
DefCompanyDTO productViewModel = new DefCompanyDTO();
var product = new DefCompany
{
//same problem of all entites getting no value from grid
Id = productViewModel.Id, // getting no value from grid
CurrentCurrencyCode = productViewModel.CurrentCurrencyCode,
ShortName= productViewModel.ShortName,
FullName= productViewModel.FullName,
ContactPerson= productViewModel.ContactPerson,
Address1= productViewModel.Address1,
CompanyCity= productViewModel.CompanyCity,
CompanyState= productViewModel.CompanyState,
CompanyCountry= productViewModel.CompanyCountry,
ZipPostCode= productViewModel.ZipPostCode,
TelArea= productViewModel.TelArea
};
result.Add(product);
data.DefCompanies.Add(product);
data.SaveChanges();
}
}
here is my viewmodel code
document.onreadystatechange = function () {
var viewModel = kendo.observable({
products: new kendo.data.DataSource({
schema: {
//data:"Data",
total: "Count",
model: {
Id: "Id",
fields: {
Id: { editable: true, type: "int" },
ShortName: { editable:true, type: "string" },
FullName: { editable: true, type: "string" },
ContactPerson: { editable: true, type: "string" },
CurrentCurrencyCode: { editable: true, type: "int" },
Adress1: { editable: true, type: "string" },
CompanyState: { editable: true, type: "string" },
CompanyCity: { editable: true, type: "string" },
CompanyCountry: { editable: true, type: "string" },
ZipPostCode: { editable: true, type: "string" },
TelArea: { editable: true, type: "string" }
}
}
},
batch: true,
transport: {
read: {
url: "/api/Companies/GetAllCompanies",
dataType: "json"
},
create:{
url: "/api/Companies/SaveDefCompny",
dataType: "json"
},
update: {
url: "/api/Companies/SaveDefCompny", // here you need correct api url
dataType: "json"
},
destroy: {
url: "/api/Companies/Delete", // here you need correct api url
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data) {
return kendo.stringify(data) ;
}
}
}
})
});
kendo.bind(document.getElementById("example"), viewModel);
}
how should i pass my inline kendo grid values to my controller so that it save it in database?
Check Kendo documentation and see what kind of parameters SaveDefCompny should expect. You should then be able to read whatever you require using those parameters.
url: "/api/Companies/SaveDefCompny", dataType: "json"
This most likely is sending your controller method the required data in json format.
Again: your answer lies in the Kendo documentation.
EDIT:
See this and this.
From their example:
public ActionResult Products_Create([DataSourceRequest]DataSourceRequest request, ProductViewModel product)
{
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
// Create a new Product entity and set its properties from the posted ProductViewModel
var entity = new Product
{
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Add the entity
northwind.Products.Add(entity);
// Insert the entity in the database
northwind.SaveChanges();
// Get the ProductID generated by the database
product.ProductID = entity.ProductID;
}
}
// Return the inserted product. The grid needs the generated ProductID. Also return any validation errors.
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
I have Odata WebApi, and I want to populate my dropdownlist with data from there.
I have datasource:
var postsDataSource = new kendo.data.DataSource({
type: 'odata',
serverFiltering: true,
transport: {
read: {
url: "/odata/Posts",
dataType: "json"
},
},
schema: {
model: kendo.data.Model.define({
Id: "Id",
RegionId: "RegionId"
}),
data: function (res) {
debugger;//this code is inaccessible!
console.log(res);
return res.value;
}
},
});
and dropdownlist like this:
var posts = $("#searchPost").kendoDropDownList({
optionLabel: "Выберите регион...",
dataTextField: "NameRu",
dataValueField: "Id",
dataSource: postsDataSource,
}).data("kendoDropDownList");
This part of code executes odata query and return me the following json response in the firebug's console:
{
"odata.metadata":"http://localhost:11029/odata/$metadata#Posts","odata.count":"13","value":[
{
"Id":0,"Number":"Lenina45","RegionId":1,"NameRu":"\u041b\u0435\u043d\u0438\u043d\u0430 45","NameKz":"\u041b\u0435\u043d\u0438\u043d\u0430 45","ShortName":"\u041b\u0435\u043d\u0438\u043d\u0430 45","DateBegin":null,"DateEnd":null,"OptimisticLockField":null
},{
"Id":1,"Number":"Zhumabaeva15","RegionId":2,"NameRu":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","NameKz":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","ShortName":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","DateBegin":null,"DateEnd":null,"OptimisticLockField":null
},
.....
]
}
Right after this response I am getting the following strange error:
TypeError: d.d is undefined;
And dropdownlist doesn't show me above json response.
When I populated kendo grid with odata web api, the following code in datasource solved my problem:
schema: {
data: function (res) {
return res.value;
}
},
but now, when I use it for dropdownlist it doesn't work at all, it's inaccessible.
PS> Sorry for my bad English.
You Data Is on the inner object "value" on your response , your response consist on page size , metadata url so we need to prase the data that kendo dataSource can understand here is a exsample
: Note Remove "type: 'odata'" and check , since you are saying the dataSource where the Data is from the Data function no need of it as I think.
var postsDataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: "/odata/Posts",
dataType: "json"
},
},
schema: {
model: {
Id: "Id",
fields: {
Id: { type: "number" },
NameRu: { type: "string" },
NameKz: { type: "string"},
ShortName: { type: "string" }
}
},
data: function (response) {
return response.value;
},
total: function(response) {
return response.odata.count;
}
},
});
try this hope this helps.
I have looked at an example Kendo grid here, and another one on Codeproject and a thread on this site, but I don't seem to find the error. I'm not very knowledgeable with javascript or HTML, so I expect it to be a simple mistake on my part.
Here is the code I have so far:
$(document).ready(function () {
var baseURL = "/api/LeaveTypes",
leaveTypes = new kendo.data.DataSource({
autoSync: true,
transport: {
read: {
url: baseURL + "?getAll=true",
dataType: "jsonp",
type: "GET"
},
update: {
url: baseURL,
dataType: "jsonp",
type: "POST"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id: "Id",
fields: {
Id: {type: "number", editable: false, validation: { required: true } },
Description: { type: "string", editable: false, validation: { required: true } },
IsEssLeaveType: { type: "boolean", editable: true, },
ColourRGB: {type: "string", editable: true, nullable: true }
}
}
}
});
$(".leavetypesgrid").kendoGrid({
dataSource: leaveTypes,
toolbar: ["save"],
columns: [{
field: "Id",
title: "Leave Type ID"
}, {
field: "Description",
title: "Leave Type"
}, {
field: "IsESSLeaveType",
template: '<input type="checkbox" #= IsESSLeaveType ? "checked=checked" : "" # ></input>',
title: "Flagged for ESS",
}, {
field: "ColourRGB",
title: "Colour"
}
],
scrollable: false,
editable: {
update: true
}
});
});
I am trying to get it to work in JSFiddle, but since I'm quite new to it, I'm still struggling to get the data source disconnected from the Controller that I'm currently using to populate the grid with, and connecting it to sample data.
Here is the Controller's Post method:
public SimpleResult Post(List<LeaveCalendarLeaveType> leaveTypesList)
{
return ESSLeaveDataManager.SaveLeaveTypes(leaveTypesList);
}
Any help will be much appreciated! :)
The first thing that I noticed is that you have two data sources defined. One called dataSource and another called leaveTypes. You are only setting the datasource on your grid to leaveTypes.
Did you configure your MVC route so that it goes to the action named Post() when /api/LeaveTypes is called? Otherwise, the url for the update config should be /api/LeaveTypes/Post