KendoUI Grid Update Issue - javascript

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

Related

Uncaught TypeError: $(...).html(...).modal is not a function

I am getting above error when i try to show id in pop up window.
my code are below
grid.cshtml
<script src="#Url.Content("~/js/Grid.js")" type="text/javascript"></script>
<div id="login_for_review" class="modal hide" role="dialog"></div>
grid.js
var init = function () {
var Grid = $("#Grid");
Grid.kendoGrid({
dataSource: {
transport: {
read: {
url: "/",
dataType: "json",
type: "GET"
},
parameterMap: function (data, type) {
if (type == "read") {
return {
limit: ,
offset: ,
sort:
}
}
}
},
schema: {
data: "Records",
total: "TotalRecordCount"
},
serverPaging: true,
pageSize: 25,
serverSorting: true,
sort: { field: "Name", dir: "asc" }
},
sortable: {
allowUnsort: false
},
pageable: true,
pageable: {
pageSizes:
},
noRecords: {
template: ""
},
columns: [
{
field: "Name",
title: "Name"
},
{
template: "<div>#if(data.id> 0){#<a href = 'javascript:void(0);' onClick='showDiv(#:TemplateId#)'>#:id# Sites</a>#} else{#ff#}#</div>",
field: "id",
title: ""
}
]
});
};
(function ($) {
$(document).trigger("o", [false, { type: "item", href: "url", text: "", showText: true }]);
init();
})(jQuery);
function showDiv(data) {
getSiteId();
console.log(data);
}
var getSiteId = function () {
$.ajax({
type: 'GET',
url: "",
dataType: 'json',
success: function (data) {
$('#login_for_review').html(data).modal('show');
// window.$('#myModal').modal();
console.log(data);
}
});
};
actually I am trying to show return id like 1,2,3.. in horizonal in a pop up when showDiv clicked .
I have followed some links and implemented in this way . Could you please help me to solve this issue ?

Kendo UI pass additional parameter when create, update and delete

When doing a create, update or delete, I need to save other form and get a id of that save function and pass that id as a additional parameter with these events create, update, delete
How can
I have my grid script as below
$(document).ready(function () {
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").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
toolbar: ["create"],
columns: [
{ field:"ProductName", title: "Product Name" },
{ field: "UnitPrice", title:"Unit Price", format: "{0:c}", width: "120px" },
{ field: "UnitsInStock", title:"Units In Stock", width: "120px" },
{ field: "Discontinued", width: "120px" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "popup"
});
});
I found something here but this doesn't look right
I need to post it to
[HttpPost]
public JsonResult Add(Product product, int categoryId)
{
}
Just simply inside parameterMap change return statement to this so that it would return categoryId
return kendo.stringify({
models: options.models,
categoryId: categoryIdFromSomewhere
)};
Small note, I use JSON.stringify, but quite surte if that will make any difference.

kendo ui grid sortable and crud is not working

I have followed this tutorial and brought up the sorting to work but now the crud operation is not working.
If i remove the grid sortable code then the crud is working, but no sort.
I have no idea where i am making mistake to make both sort and crud to work
THis is the code i have
$(document).ready(function () {
function dataSource_change(e) {
var data = this.data();
console.log(data.length); // displays "77"
}
var dataSource = new kendo.data.DataSource({
//pageSize: 20,
transport:{
read:{
url: function() {
return "/makes"},
dataType: "json",
cache: false
},
update: {
url: function (make) {
console.log(make)
return "/makes/"+ make.models[0].id
},
type: "PUT",
dataType: "json",
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token',jQuery('meta[name="csrf-token"]').attr("content")); }
},
destroy: {
url: function (make) {
return "/makes/"+ make.models[0].id
},
type: "DELETE",
dataType: "json"
},
create: {
url: "/makes",
type: "POST",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
console.log(options)
return{"make": options.models[0]};
}
else{
return {"make":options};
}
}
},
batch: true,
schema: {
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
name: { validation: { required: true } },
}
}
}
});
dataSource.bind("change", dataSource_change);
dataSource.fetch();
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: false,
height: 550,
toolbar: [{name: "create", text: "Add New Make"}],
columns: [
{ field:"name",title:"Makes" },
{ command: ["edit", "destroy"], title: "Action", width: "250px" }],
editable: "inline"
}).data("kendoGrid");
grid.table.kendoSortable({
filter: ">tbody >tr",
hint: $.noop,
cursor: "move",
placeholder: function(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
},
container: "#grid tbody",
change: function(e) {
console.log(grid)
var skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
data = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
var updated_order = []
$('tbody tr').each(function(i){
updated_order.push({ name: $(this).children('td:first').text(), position: i+1 });
});
controller_name = $('#controller_name').val();
$.ajax({
type: "PUT",
url: '/sort',
data: { order: updated_order, controller_name: controller_name }
});
grid.dataSource.remove(dataItem);
grid.dataSource.insert(e.newIndex, dataItem);
}
});
});

Kendo UI / set datasource from ajax call

I start using Kendo UI editable grid, but I want to set my own datasource coming from php script which echoes a array of objects (copy/paste from the original Kendo UI datasource).
The thing is nothing populate the grid.
Here is the content of my html file.
` Back
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "http://localhost/telererik-kendoui",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "../../datasource.php",
dataType: "json",
type:"GET",
contentType: "application/json; charset=utf-8",
cache: false
},
/* 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").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 },
{ field: "Discontinued", width: 120 },
{ command: "destroy", title: " ", width: 120 }],
editable: true
});
});
</script>
</div>`
The content of my datasource.php file is as follow
<?php
echo "[{'ProductID':1,'ProductName':'Chai','UnitPrice':18,'UnitsInStock':39,'Discontinued':false},{'ProductID':2,'ProductName':'Chang','UnitPrice':19,'UnitsInStock':17,'Discontinued':false},{'ProductID':3,'ProductName':'Aniseed Syrup','UnitPrice':10,'UnitsInStock':13,'Discontinued':false}]"?>
Any help on that?
im not really familier with php but with your data in the php file i have done a demo for you .
call the dataSource read as a function so you have much more flexibility to do anyting for the result you get.
read: function (options) {
var result=[{'ProductID':1,'ProductName':'Chai','UnitPrice':18,'UnitsInStock':39,'Discontinued':false},{'ProductID':2,'ProductName':'Chang','UnitPrice':19,'UnitsInStock':17,'Discontinued':false},{'ProductID':3,'ProductName':'Aniseed Syrup','UnitPrice':10,'UnitsInStock':13,'Discontinued':false}]
options.success(result);
}
http://jsfiddle.net/chanaka1/ank22b0n/
you may look the kendo doc for how to return a json from a php file here : http://docs.telerik.com/kendo-ui/php/widgets/combobox/remote-binding#create-php-file-which-returns-json

kendo ui crud operations using only jquery and Ajax

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

Categories

Resources