Values cannot pass from kendo grid to Entity class? - javascript

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));
}

Related

Update the values of a Kendo grid column which is populated by remote data

I have a Kendo grid which is rendered as soon as the page loads. The grid is populated by remote data.
logMonitoringGrid.kendoGrid({
dataSource: {
batch: true,
transport: {
read: {
url: window.$vars['webApiHost'] + "logs",
dataType: "json",
}
},
serverFiltering: false,
serverPaging: false,
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number" },
TTId: { type: "string" },
LUId: { type: "number" },
Level: { type: "string" },
Server: { type: "string" },
Thread: { type: "number" },
Message: { type: "string" },
Ip: { type: "string" },
RId: { type: "string" },
Timestamp: { type: "date" }
}
}
}
},
columns: columnObjects
});
var lGrid = logMonitoringGrid.data("kendoGrid");
There's another API which has the data of all the tenants like this (JSON)
{
Id: 5196
Name: "unittest"
ContactEmail: "admin#unittest.com"
Theme: "default"
DefaultLocale: "en-US"
IsInternal: false
}
I need to replace the Tenant Id of each row of the grid with their corresponding tenant names. The remote data of the grid does not send any tenant names with it. That's why I am creating a map of all the tenant ids and their names.
var tenantData = new kendo.data.DataSource({
transport: {
read: {
beforeSend: function (xhr) {
o9Util.setRequestHeaders(xhr);
},
url: crudUrl("tenants"),
dataType: "json"
}
}
});
var myMap = new Map();
tenantData.fetch(function () {
var data = tenantData.data();
for (var i = 0; i < data.length; i++) {
myMap.set(data[i].Id, data[i].Name);
}
})
Now I'm updating the grid column like this
lGrid.dataSource.fetch(function () {
var data = this.data();
for (var i = 0; i < data.length; i++) {
for (var [key, value] of myMap.entries()) {
if (parseInt(data[i].TTId) === key) {
data[i].set("TTId", value);
}
}
}
})
This approach works but takes some time to change the values of the column whenever the page loads. Moreover the page becomes unresponsive after some time. Is there any other way I can update the grid as soon as the page loads?
A suggest the following:
Make your API(tenants) call before Kendo's call. Remember to initialize the grid when this requests finishes, that means, on DataSource's requestEnd event;
Initialize your grid;
In the Grid's dataSource.schema.parse you set the values you want. Example:
logMonitoringGrid.kendoGrid({
dataSource: {
schema: {
parse: function(data) {
let tenantJsonData = tenantData.data().toJSON();
data.forEach(item => {
let tenantItem = tenantJsonData.find(ti => ti.Id === item.TTId);
if (tenantItem) {
item.TTTId = tenantItem.Name;
}
});
return data;
}
}
}
}
I didn't tested it, but it should work.

Kendo dataSource.add - "Id is not defined"

I'm trying to add some items to a Kendo DataSource to then display in the grid. However, every time I try to save I get Reference Error: Id is not defined.
At first I thought it was because I didn't include Id in my schema but I checked and it looks alright.
var viewModel = new kendo.observable({
orgDataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/Organization/GetAll",
dataType: "json"
},
update: {
url: "/Host/Organization/Edit",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
},
create: {
url: "/Host/Organization/Create",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
},
destroy: {
url: "/Host/Organization/Delete",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
}
},
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number", editable: false, nullable: true },
Name: { type: "string" },
LicenseExpiration: { type: "date" },
LicenseNumber: { type: "number" },
Active: { type: "boolean" },
CreateDate: { type: "date" },
LastModDate: { type: "date" },
AvailableLicenses: { type: "string" },
State: { type: "string" }
}
},
errors: "errorMsg"
},
pageSize: 20,
error: function (e) {
toastr.options = {
"positionClass": "toast-bottom-full-width"
};
toastr.error("There was an error: " + e.errors, "Uh, Oh!");
this.cancelChanges();
},
serverPaging: false,
serverFiltering: false,
serverSorting: false
}),
reloadOrganizations: function () {
this.get("orgDataSource").read();
},
onOrgSave: function (e)
{
var uid = $('input[name="OrgRowUID"]').val();
var tr = $('tr[data-uid="' + uid + '"]'); // get the current table row (tr)
var name = $('input[name="Name"]').val();
var licenseNumber = $('input[name="LicenseNumber"]').val();
var licenseExpiration = $('input[name="LicenseExpiration"]').val();
var email = $('input[name="Email"]').val();
var state = $('input[name="State"]').val();
var logo = $('input[name="ImageUrl]').val();
var active = $('input[name="Active"]').is(":checked");
// get the data bound to the current table row
var orgGrid = $("#OrganizationGrid").data("kendoGrid");
var data = orgGrid.dataItem(tr);
if (data == null)
{
viewModel.orgDataSource.add({ Name: name, LicenseNumber: licenseNumber, LicenseExpiration: licenseExpiration, Email: email, State: state, ImageUrl: logo, Active: active })
orgGrid.saveChanges();
viewModel.orgDataSource.sync();
viewModel.reloadOrganizations();
} else {
data.set("Name", name);
data.set("LicenseNumber", licenseNumber);
data.set("LicenseExpiration", licenseExpiration);
data.set("Email", email);
data.set("State", state);
data.set("ImageUrl", logo);
data.set("Active", active);
}
$("#orgCreateModal").modal('hide');
$("#orgEditModal").modal('hide');
}
});
The error is occurring on this line:
viewModel.orgDataSource.add({ Name: name, LicenseNumber: licenseNumber, LicenseExpiration: licenseExpiration, Email: email, State: state, ImageUrl: logo, Active: active });
The error in FireBug is:
Reference Error: Id is not defined - kendo.all.min.js line 25 > function
It's throwing that error because you're not setting "Id" to anything in your datasource. I had a similar problem a while back and Telerik said you have to give 'id' a valid unique value because they use that internally to keep things straight in the datasource. In your case, you are setting your schema id to "Id", but it doesn't look like your datasource has an "Id" field. I ended up just dumping a guid in there and it fixed my problem.

Getting a string on an update request in KendoUI datasource

I have a pretty simple grid with data source that retrieves data correctly
For that cause I have a schema.parse function defined
The problem is that when I try to update/create new row the schema.parse() called again and the parameter that is passed to it is a string that contains the HTML of my page. cannot really get what the hell is going on there.
thanks
var _dataSource = new kendo.data.DataSource({
transport: {
read: {
dataType: "json",
url: layerDefProvider.getLayerUrlById("surveys") + "/query",
data: {
f: "json",
//token: token,
outFields: "*",
//outSR: 3857,
where: "1=1"
},
type: "POST"
},
create: function (options) {
console.debug("called");//never gets called
},
update: function (options) {
console.debug("called");//never gets called
},
destroy: function (options) {
console.debug("called");//never gets called
}
},
filter: {
field: "OBJECTID", operator: "eq", value: 0
},
schema: {
data:function(response) {
},
parse: function (data) {//on loading it is fine, on updating the data param is a string of my HTML of the page
var rows = [];
var features = data.features;
if (!features) {
return [];
}
for (var i = 0; i < features.length; i++) {
var dataRow = {};
dataRow.OBJECTID = features[i].attributes.OBJECTID;
dataRow.Name = features[i].attributes.Name;
dataRow.Date = features[i].attributes.Date;
dataRow.Comment = features[i].attributes.Comment;
rows.push(dataRow);
}
return rows;
},
model: {
id: "OBJECTID",
fields: {
OBJECTID: { type: "number", editable: false },
Name: { type: "string" },
Date: { type: "string" },
Comment: { type: "string" }
}
}
}
});
var _surveysPicker = $(config.table).kendoGrid({
toolbar: ["create","save"],
editable: true,
dataSource: _dataSource,
height: 300,
sortable: true,
selectable: "multiple",
columnMenu: true,
resizable: true,
columns: [{
field: "OBJECTID",
width: 40
}, {
field: "Name",
width: 40
}, {
field: "Date",
width: 40
}, {
field: "Comment",
width: 100
}]
});
You need to move your parse function inside read event if you need to parse data only on read action.

Kendo datasource shema.data does not work for dropdownlist

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.

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