Hi ,
I am using Telerik.UI.for.AspNet.Core version 2020.3.915
I have created dynamic kendo grid using jquery. my model will vary depending in columns from db. So I am gettign the data as json from DB and creating my grid. i am able to achieve it, But when I try to edit the column values, I am unable to call the controller mthod with proper values from UI. I wanted to do batch edit. But when I use the below code , my controller is getting called multiples times for each edit. Also ,t he value passed is not a proper array. It is in Json format . but looks like { Steer_ID:23,SteerMaximun:34,.......} . Please hepl me to send all the row values that are edited in jason format to the comtroller.
js:
function generateMarginSnapshotColumns(gridData, isEditable) {
var isdisable = "";
if (!isEditable)
isdisable = "disabled";
// initiate the column array
var columns = [];
var groupedColumns = [];
//initiate a counter, used to work out which column we are dealing with
var columnIndex = 0;
var groupedColumnIndex = 0
// define the desired order of the columns
var columnOrder = {
KPI_UNIT_CODE: 1,
KPI_CLASS_DISPLAY_NAME: 2,
STEER_VALUE: 3,
STEER_MAXIMUM_VALUE: 4,
STEER_MINIMUM_VALUE: 5,
DIRECTION_CODE: 6,
MARGIN_DELTA: 7,
DOI: 8,
ENS: 9,
CREATION_USER_ID: 50,
CREATION_DATE: 51,
LAST_UPDATE_USER_ID: 52,
LAST_UPDATE_DATE: 53
// Add more columns and their desired order as needed
};
var NoDisplayColumns = ["STEER_ID", "KPI_SITE_HIERARACHY_ID", "KPI_CLASS_GROUP_CODE", "ACKNOWLEDGEMENT_IND", "KPI_AREA_NAME", "KPI_UNIT_NAME"];
// iterate all of the data items in the first element of the returned JSON data
for (var dataItem in gridData) {
var colTitle = dataItem.replace('_', ' ');
var dataItemField = dataItem;
// create the columns and set up the look and feel - first three are always present and fixed in place
switch (dataItemField) {
case "CREATION_USER_ID":
case "CREATION_DATE":
case "LAST_UPDATE_USER_ID":
case "LAST_UPDATE_DATE":
columns.push({ field: dataItemField, title: colTitle, width: 100, locked: true, hidden: true, headerAttributes: { style: "text-align: left" }, order: columnOrder[dataItemField], editable:true });
break;
case "KPI_UNIT_CODE":
columns.push({ field: dataItemField, title: "UNIT", width: 200, locked: true, headerAttributes: { style: "text-align: left" }, order: columnOrder[dataItemField], editable: true });
break;
case "KPI_CLASS_DISPLAY_NAME":
columns.push({ field: dataItemField, title: "KPI", width: 200, locked: true, headerAttributes: { style: "text-align: left" }, order: columnOrder[dataItemField],editable:true });
break;
case "DOI":
columns.push({ field: dataItemField, title: "Daily Opertor Input", width: 200, headerAttributes: { style: "text-align: left" }, order: columnOrder[dataItemField], editable: !isEditable });
break;
case "ENS":
columns.push({ field: dataItemField, title: "ENS Input", width: 200, headerAttributes: { style: "text-align: left" }, order: columnOrder[dataItemField], editable: !isEditable });
break;
default:
if (columnOrder.hasOwnProperty(dataItemField)) {
columns.push({
field: dataItemField,
title: colTitle,
width: 120,
headerAttributes: { style: "text-align: center;white-space: normal" },
attributes: { style: "text-align: center" },
order: columnOrder[dataItemField],
editable: !isEditable
//template: "<div><input " + isdisable + " type='textbox' onchange='javascript:SaveSteerRow(\"" + colTitle + "\", #:Steer_ID#,this)' value='#:" + dataItemField + "#' > </input> <div id='spn#:Steer_ID#" + dataItemField + "'></div></div>"
});
}
else {
if (NoDisplayColumns.includes(dataItemField))
break;
columns.push({
field: dataItemField,
title: colTitle,
width: 120,
hidden: true,
headerAttributes: { style: "text-align: center;white-space: normal" },
attributes: { style: "text-align: center" },
order: columnOrder[dataItemField],
editable: !isEditable
//template: "<div><input " + isdisable + " type='textbox' onchange='javascript:SaveSteerRow(\"" + colTitle + "\", #:Steer_ID#,this)' value='#:" + dataItemField + "#' > </input> <div id='spn#:Steer_ID#" + dataItemField + "'></div></div>"
});
}
break;
}
// increment the counter so we know when we are done with fixed columns
columnIndex += 1;
}
return columns;
}
function SaveSteerRow(colName, steerId, txtBox) {
if (txtBox.checked) {
txtBox.value = '1';
}
else {
txtBox.value = '0';
}
var fd = new FormData();
fd.append("steerId", steerId);
fd.append("colName", colName);
var id = "spn" + userId + colName.replace(' ', '_');
$.ajax({
async: true,
type: "POST",
url: "/MarginSteerConstraint/UpdateSnapShot",
beforeSend: function (xhr) {
$("#" + id).html("Saving...");
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fd,
contentType: false,
processData: false,
success: function (response) {
$("#" + id).html("");
console.log('UpdateSnapShot - Success');
},
error: function (e) {
$("#" + id).html("Error...");
console.log("Error Logged : ")
console.log(e);
}
});
}
var grid;
function LoadSnapShotGrid() {
var siteId = selectedSnapSite.SiteType == "Unit" ? selectedSnapSite.SiteHierarchyId : selectedSnapSite.ID;
$("#grdSnap").html("");
$.ajax({
'async': true,
'type': "GET",
'global': false,
'url': "/MarginSteerConstraint/ReadSnapShot",
'data': { 'request': "", 'siteType': selectedSnapSite.SiteType, 'ID': siteId, 'target': 'arrange_url', 'method': 'method_target' },
'success': function (response) {
console.log('ReadSnapShot - Success');
snapShotData = JSON.parse(response.SnapShot);
var isEditable = response.IsEditable;
generateGrid(snapShotData, isEditable);
//kendo.ui.progress(windowWidget.element, false);
}
});
//bindSaveButtonEvent();
}
function bindSaveButtonEvent() {
// Unbind any existing event handlers to avoid multiple bindings
$("#grdSnap").off("click", ".k-grid-save-changes");
// Bind the event handler for the "save" button
$("#grdSnap").on("click", ".k-grid-save-changes", function () {
// Code to handle the button click event
var grid = $("#grdSnap").data("kendoGrid");
grid.dataSource.sync();
});
}
LoadSnapShotGrid();
function generateModel(gridData) {
var model = {};
model.id = "STEER_ID";
model.id = "KPI_SITE_HIERARCHY_ID";
model.id = "KPI_CLASS_GROUP_CODE";
var fields = {};
for (var property in gridData) {
//if (property.indexOf("ID") !== -1) {
// model["id"] = property;
//}
var propType = typeof gridData[property];
if (propType === "number") {
fields[property] = {
type: "number",
//validation: {
// required: true
//}
};
if (model.id === property) {
fields[property].editable = false;
//fields[property].validation.required = false;
}
} else if (propType === "boolean") {
fields[property] = {
type: "boolean"
};
} else if (propType === "string") {
var parsedDate = kendo.parseDate(gridData[property]);
if (parsedDate) {
fields[property] = {
type: "date"
//validation: {
// required: true
//}
};
isDateField[property] = true;
} else {
fields[property] = {
type: "string"
//validation: {
// required: true
//}
};
}
} else {
fields[property] = {
//validation: {
// required: true
//}
};
}
}
model.fields = fields;
return model;
}
// function takes the JSON data, and dynamically produces a column set, the data schema and binds the grid
function generateGrid(gridData, isEditable) {
var model = generateModel(gridData[0]);
console.log(model);
var columns = generateMarginSnapshotColumns(gridData[0], isEditable);
console.log(columns);
// set up the grid
grid = $("#grdSnap").kendoGrid({
toolbar: ["save","cancel","excel"],
excel: {
fileName: "MarginSteerSnapshot",
filterable: true
},
dataSource: {
data: gridData,
pageSize: 20,
autoSync: false,
schema: {
model: model
},
transport: {
read: function (options) {
options.success(gridData);
},
update: function (options) {
debugger;
var fd = new FormData();
fd.append("steerData", kendo.stringify(options.data));
//alert(kendo.stringify(options.data));
$.ajax({
url: "/MarginSteerConstraint/UpdateSnapShot",
//dataType: "json",
type: "POST",
contentType: false,
processData: false,
beforeSend: function (xhr) {
// $("#" + id).html("Saving...");
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fd,
success: function (response) {
// Handle the success response
console.log(response);
options.success(response); // Notify the transport that the update was successful
},
error: function (xhr, status, error) {
// Handle the error response
console.error(error);
options.error(xhr, status, error); // Notify the transport about the error
}
});
}
},
parameterMap: function (options, operation) {
if (operation === "update") {
console.log("in parameter map");
console.log(JSON.stringify(options.data));
//var updatedData = options.data; // Get the updated data object
//alert(updatedData);
//// Convert the updatedData object to JSON
//var SnapShot = kendo.stringify(updatedData);
// Create a dynamic object to send to the controller method
//var SnapShotViewModel = {
// "SnapShot": kendo.stringify(options.data),
// "isEditable": true
//};
// Convert the dynamicObject to JSON
//var dynamicJson = JSON.stringify(SnapShotViewModel);
return JSON.stringify(options.data);
}
}
},
pageable: {
refresh: true,
pageSizes: [20,50,100, 200, "all"],
},
columnMenu: true,
columns: columns,
sortable: true,
filterable: true,
width: "auto",
resizable: true,
editable: "incell",
batch:true,
serverOperation :false,
pageSize: 20
});
}
UI:
<div>
<div>
<div id="grdSnap"></div>
</div>
</div>
Controller:
[HttpPost]public IActionResult UpdateSnapShot( string steerData)
{
try
{
if (accessType.ToString() == AccessType.ReadWrite.ToString() ||
accessType.ToString() == AccessType.FullAccess.ToString())
{
JObject json = JObject.Parse(steerData);
dynamic snap = JArray.Parse(steerData);
//dynamic dynJson = JsonConvert.DeserializeObject(steerData);
MarginSteerSnapShot snapShot;
for(int i = 0; i < snap.Count; i++)
{
snapShot = new MarginSteerSnapShot();
dynamic snapData= snap[i];
snapShot.KPI_CLASS_GROUP_DISPLAY_NAME = snapData.KPI_CLASS_GROUP_DISPLAY_NAME;
}
//foreach (JProperty property in json.Properties())
//{
// string propertyName = property.Name;
// JToken propertyValue = property.Value;
// snapShot=new MarginSteerSnapShot();
// //get the comments for the site.
// // create object for Model and assign the values based on property name
// // compare property name and assign in comment list.
// // Now you can use the property name and value as needed
// Console.WriteLine($"Property Name: {propertyName}");
// Console.WriteLine($"Property Value: {propertyValue}");
//}
//if (records != null && ModelState.IsValid)
//{
// records.All(model =>
// {
// db.UpdateSnapShot(model);
// _logger.LogInformation("Margin & Steer snapshot updayed {0}", JsonConvert.SerializeObject(model));
// return true;
// });
//}
try
{
db.execSP();
}
catch (Exception ex)
{
_logger.LogError("Error while updating snap shot- Margin & Steer Page {0}", ex.Message);
}
}
//return Json(records.ToDataSourceResult(request, ModelState));
return Json(new SnapShotViewModel() { });
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
return Json(ex.Message);
}
}