Kendo grid row disapeared when editing after adding a row - javascript

I defined a kendo grid like that, and somehow after adding a row, the first edit click I do (before sending to the server) the row I just added is disappearing, and after refreshing its still there.
any suggestions why its happening?
$("#actionGrid").kendoGrid({
scrollable: true,
height: "200px",
toolbar: [{name: "create", text: "Add"}],
editable: {
mode: "inline",
confirmation: false
},
columns: [
{ field: "order", title: "Order", width: 80 },
{ field: "action", title: "Action name"},
{ command: ["edit", "destroy"], width: 100 }
],
dataSource: {
schema: {
model: {
id:"taskId",
fields: {
taskId: { type:"number" },
order: { type: "number", validation: { min: 0 } },
action: {}
}
}
},
transport: {
read: {
dataType: "json",
type: "GET",
contentType: "application/json",
url: "action/readByPId?pId=" + pId
},
destroy: {
dataType:"json",
type:"POST",
contentType:"application/json",
url: "action/delete"
},
update: {
dataType: "json",
type: "POST",
contentType: "application/json",
url: "action/update"
},
create: {
dataType: "json",
type: "POST",
contentType: "application/json",
url: "action/update"
},
parameterMap:function parameterMap(options,type) {
if(type !== "read"){
return JSON.stringify(options);
}
}
},
sort: { field: "order", dir: "asc" }
}
});

Kendo Grid have straight rules .Like whenever create new record ,have to return updated list to client side call . please make sure whether that updated record is returning or not.
IF you doing online offline feature of kendo UI . then follow this following demo.
https://demos.telerik.com/kendo-ui/grid/offline
you have not mentioned the data communication method . but if you are doing purly custom way then you have to update datasoure after doing any operation .Please put following code to get update with new data .
$('#GridName').data('kendoGrid').dataSource.read(); <!-- first reload data source -->
$('#GridName').data('kendoGrid').refresh(); <!-- refresh current UI -->

Related

KendoUI Grid Update Issue

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

Kendo UI - js grid destroy function not triggered

This is my grid:
$(document).ready(function () {
datasource = new kendo.data.DataSource({
transport: {
read: {
url: '/Discount/Get',
dataType: "json",
},
update: {
url: '/Discount/Update',
dataType: "json",
type: "POST"
},
destroy: {
url: '/Discount/Delete',
dataType: "json",
type: "POST"
},
create: {
url: '/Discount/Add',
dataType: "json",
type: "POST"
},
parameterMap: function (options, operation) {
console.log(operation);
if (operation !== "read") {
return options;
}
}
},
schema: {
model: {
id: "Id",
fields: {
TopItemName: { type: "string" },
DiscountValue: { type: "number" },
}
}
}
});
$("#grid").kendoGrid({
dataSource: datasource,
batch: true,
toolbar: ["create", "save", "cancel"],
height: 400,
navigatable: true,
pageable: true,
columns: [
{
field: "TopItemName",
editor: topItemDropDown,
template: "#=TopItemName#"
},
{
field: "DiscountValue",
format: "{0:p0}",
editor: function (container, options) {
$("<input name='DiscountValue'>")
.appendTo(container)
.kendoNumericTextBox(
{
min: 0,
max: 1.00,
step: 0.01
});
}
},
{
command: "destroy",
title: " ",
width: 150
}],
editable: true
});
function topItemDropDown(container, options) {
console.log(options);
$('<input required data-text-field="TopItemName" data-value-field="TopItemName" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: {
serverFiltering: true,
transport: {
read: {
url: '/Discount/GetTopItemName',
dataType: "json",
type: "POST",
contentType: "application/json"
}
}
}
});
}
});
and somehow when I press the delete button it deletes the row from the grid but it never calls my action method so that the row gets removed from my database. But if I after i have pressed the delete button press add new record and then save changes then it calls my add action method and my delete action method. How can I make it call the delete action method when the delete button is pressed and not when save changes is pressed?
This is how the default editing works by default - the user has to click the "Save Changes" button to submit all changes to the server.
You can do one of the following
Set the autoSync option of the data source to true
Use a different editing mode - for example inline.
Handle the remove event of the grid and call this.dataSource.sync() to automatically sync the changes.

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

Inline editing using dynamic dropdowns in kendo grid

I've been trying to make the Specification Attributes in nopCommerce editable inline using kendo grid.
If you're not a nop person, just think of an existing kendo editing grid which has one non-editable column and I want to make that column editable using dropdowns. Because of the nature of the data I'm editing, the dropdown options will be different for each row.
The current state is that the column displays correctly when not in edit mode. When in edit mode it displays the correct values, but no value is ever selected. Updating does not seem to post back to the server, and sometimes (depending upon what I try) causes javascript errors deep inside kendo.
I know next to nothing about kendo, and need to get updating with this dropdown working. Below are some code fragments (the whole thing is too long):
grid = $("#specificationattributes-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("ProductSpecAttrList", "Product", new { productId = Model.Id }))",
type: "POST",
dataType: "json"
},
update: {
url: "#Html.Raw(Url.Action("ProductSpecAttrUpdate", "Product"))",
type: "POST",
dataType: "json"
},
destroy: {
url: "#Html.Raw(Url.Action("ProductSpecAttrDelete", "Product"))",
type: "POST",
dataType: "json"
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
//ProductId: { editable: false, type: "number" },
SpecificationAttributeName: { editable: false, type: "string" },
SpecificationAttributeOptionId: { editable: true, type: "number" },
CustomValue: { editable: true, type: "string" },
AllowFiltering: { editable: true, type: "boolean" },
ShowOnProductPage: { editable: true, type: "boolean" },
DisplayOrder: { editable: true, type: "number" },
Id: { editable: false, type: "number" }
}
}
},
.......................
columns: [{
field: "SpecificationAttributeName",
title: "#T("Admin.Catalog.Products.SpecificationAttributes.Fields.SpecificationAttribute")",
width: 200
}, {
field: "SpecificationAttributeOptionId",
title: "#T("Admin.Catalog.Products.SpecificationAttributes.Fields.SpecificationAttributeOption")",
width: 200,
editor: renderDropDown, template: "#= getOptionValue(SpecificationAttributeName, SpecificationAttributeOptionId) #"
},
The method "getOptionValue" isn't included, but basically converts a value to a display-friendly label when it's not in edit mode. "renderDropDown" creates a kendoDropDownList containing the correct options for the current row.
If you return a id, value pair e.g
"{\"SpecificationAttributeOptionId\":\"0\",\"SpecificationAttributeName\":\"XYZ\"},
{\"SpecificationAttributeOptionId\":\"1\",\"SpecificationAttributeName\":\"ABC\"}"
Then you need to specify dataTextField, dataValueField. Otherwise if you return a List of string as follows, then you don't need to specify dataTextField, dataValueField and kendo will take care the rest.
"{\"SpecificationAttributeName\":\"XYZ\"},
{\"SpecificationAttributeName\":\"ABC\"}"
Hope this helps.
$("#SpecificationAttributeOptionId").kendoDropDownList({
dataTextField: "SpecificationAttributeName",
dataValueField: "SpecificationAttributeOptionId",
dataSource: {
transport: {
read: {
url: "/ControllerName/GetDropDownValueFunction",
type: "POST",
contentType: "application/json",
dataType: "json"
}
}
},
height: 100
});

Kendo UI Grid not reaching Post on Controller

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

Categories

Resources