Kendo UI Grid Inline Row not Updating for Template Columns - kendo-ui

I have a Kendo UI grid which is set to use inline editing. One column in the grid uses a template and an editor. When I make changes to this column and I click Update for the row, the update in the datasource does not get called.
The column displays a comma-separated list of text in display mode and a multi-select box in edit mode.
Here is my datasource:
var userDataSource = new kendo.data.DataSource({
autoSync: true,
transport: {
read: {
url: "#Url.Action("ManagedUsers", "Manage")" + $("#suppliers").val(),
dataType: "json"
},
update: {
url: "#Url.Action("UpdateUser", "Manage")",
type: "POST"
},
destroy: {
url: "#Url.Action("DestroyUser", "Manage")",
type: "POST"
}
},
schema: {
model: { id: "Id" },
fields: {
Id: { editable: false, nullable: true },
Email: { validation: { required: true } },
IsAdmin: { type: "boolean" },
IsManager: { type: "boolean" },
SupplierRoles: { type: "object" }
}
}
});
And my grid:
var userGrid = $("#userGrid").kendoGrid({
columns: [{
field: "Email",
width: "35%"
},
{
field: "SupplierRoles",
title: "Roles",
template: "#= displayUserSupplierRoles(data.SupplierRoles) #",
editor: userSupplierRoleMultiSelectEditor,
filterable: false,
sortable: false
},
{
field: "IsAdmin",
title: "Admin",
hidden: "#{(!Model.User.IsAdmin).ToString().ToLower();}",
template: "#=IsAdmin ? 'Yes' : 'No' #",
width: "10%"
},
{
field: "IsManager",
title: "Manager",
hidden: "#{(!Model.User.IsManagerForCurrentSupplier).ToString().ToLower();}",
template: "#=IsManager ? 'Yes' : 'No' #",
width: "12%"
},
{ command: ["edit", "destroy"], width: "20%" }],
dataSource: userDataSource,
noRecords: true,
messages: {
noRecords: "There are no users to manage"
},
editable: "inline",
pageable: {
pageSize: 10
},
sortable: true,
filterable: true,
scrollable: true,
resizable: true
});
The editor function for the multi-select column is defined as:
function userSupplierRoleMultiSelectEditor(container, options) {
var selectedRoles = [];
for (var key in options.model.SupplierRoles) {
if (options.model.SupplierRoles[key].HasRole) {
selectedRoles.push(options.model.SupplierRoles[key].Id);
}
}
$("<select data-placeholder='Select roles...'></select>")
.appendTo(container)
.kendoMultiSelect({
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
data: options.model.SupplierRoles,
schema: {
model: { id: "Id" }
}
}
}).data("kendoMultiSelect")
.value(selectedRoles);
}
The grid is populated based upon a user action and done so within this function:
function listUserManagedUsers() {
$.ajax({
url: "#Url.Action("ManagedUsers", "Manage")" + "?supplierName=" + $("#suppliers").val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#userGrid").data("kendoGrid").dataSource.data(data);
}
});
}
For completeness, I'll include the view model for the grid:
public class ManagedUserViewModel
{
public string Id { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public bool IsManager { get; set; }
public List<UserSupplierRole> SupplierRoles { get; set; }
}
public class UserSupplierRole
{
public int Id { get; set; }
public string Name { get; set; }
public bool HasRole { get; set; }
}
When in edit mode, changing the email and clicking on Update calls Update on the datasource. After altering the multiselect and pressing update does not trigger the update call on the datasource.
Can anyone help me with what am I doing wrong?
Thanks!

OK. So I figured out what was going wrong.
Essentially, it was when I bound to the multiselect widget.
Here is the new code:
function userSupplierRoleMultiSelectEditor(container, options) {
$("<select data-placeholder='Select roles...' multiple='multiple' data-bind='value:SupplierRoles'></select>")
.appendTo(container)
.kendoMultiSelect({
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
transport: {
read: function(op) {
var roleCache = localStorage.getItem("roles");
if (roleCache != null || roleCache != undefined) {
op.success(JSON.parse(roleCache));
} else {
$.ajax({
url: "#Url.Action("Roles", "Manage")",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
localStorage.setItem("roles", JSON.stringify(data));
op.success(data);
}
});
}
}
}
}
});
}
I added the data-bind attribute to the select tag and I set it to the roles that the user has. I then set the read in the datasource to get all of the roles.
Once these two pieces were hooked up (with a slight change of the view model), the grid would stay synchronized with its state).

Related

How to get field value when edit data in Kendo Ui treelist

I'm new in Kendo UI,and i have a question. Now i'm use TreeList / Editing and how to auto load value to other field when i edit value to first field ?
example:
1.serial number: 123456789
2.name : test
when i edit serial number 123456789 to first field and auto load name to second field.
To set the value of column B based on change made to a column A, you need to edit the model bound to the tree list. For this do the following:-
Handle edit event of the tree list. On this save the model to a
local variable.
Add an editor
template
to column A. On the select event set the value of model.
Below is a working code snippet:-
<div id="treelist"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service";
var model= null;
var employeesData=[{"EmployeeId":101,"FirstName":"Daryl","LastName":"Sweeney"},
{"EmployeeId":202,"FirstName":"Guy","LastName":"Wooten"},
{"EmployeeId":303,"FirstName":"Priscilla","LastName":"Frank"},
{"EmployeeId":404,"FirstName":"Ursula","LastName":"Holmes"},
{"EmployeeId":505,"FirstName":"Anika","LastName":"Vega"}];
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/EmployeeDirectory/All",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
schema: {
model: {
id: "EmployeeId",
parentId: "ReportsTo",
fields: {
EmployeeId: { type: "number", nullable: false },
ReportsTo: { nullable: true, type: "number" },
FirstName: { validation: { required: true } },
HireDate: { type: "date" },
Phone: { type: "string" },
HireDate: { type: "date" },
BirthDate: { type: "date" },
Extension: { type: "number", validation: { min: 0} },
Position: { type: "string" }
},
expanded: true
}
}
});
$("#treelist").kendoTreeList({
dataSource: dataSource,
toolbar: [ "create", "save", "cancel" ],
editable: "incell",
height: 540,
dataBound: function (e) {
var items = e.sender.items();
for (var i = 0; i < items.length; i++) {
var dataItem = e.sender.dataItem(items[i]);
var row = $(items[i]);
if (dataItem.isNew()) {
row.find("[data-command='createchild']").hide();
}
else {
row.find("[data-command='createchild']").show();
}
}
},
edit: function(e) {
model = e.model;
},
columns: [{
field: "EmployeeId",
expandable: true,
title: "Serial Number",
width: 180,
editor: function(container, options) {
// create an input element
var input = $("<input/>");
// set its name to the field to which the column is bound ('lastName' in this case)
input.attr("name", options.field);
// append it to the container
input.appendTo(container);
// initialize a Kendo UI AutoComplete
input.kendoAutoComplete({
dataTextField: "EmployeeId",
dataSource: employeesData,
select: function(e) {
if(model !=null){
model.FirstName = e.dataItem.FirstName;
model.LastName = e.dataItem.LastName;
}
}
});
}
},
{ field: "FirstName", title: "First Name", width: 100 },
{ field: "LastName", title: "Last Name", width: 100 },
{ field: "Position", width: 100 },
{ field: "Phone", title: "Phone", width: 100 },
{ field: "Extension", title: "Ext", format: "{0:#}", width: 100 },
{ command: [{name: "createchild", text: "Add child"},"destroy" ], width: 240 }]
});
});
</script>
You can trigger your function when the row is being saved or when the edit field is being changed. Take a look at the list of events here and choose when exactly you want to make the changes. https://demos.telerik.com/kendo-ui/treelist/events
here is a example how to all a function when saving the changes: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist/methods/saverow
I´m not sure witch edit method you are using (inline, inCell or Popup edit mode) each method can use events like saveRow, beforeEdit...
Check all the events documentation here: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist#events

How to retrieve a text value in a kendo drop down list within a kendo grid cell but still pass the ID in CRUD

I'm having a problem finding a solution related to the Kendo Grid.
I am rendering a kendo dropdown list within a cell of a Kendo Grid. It appears to look fine and all, until the user focuses off or tabs off of the dropdown within the cell. The red hash shows that a change was made, but it's showing the data-value-field of the kendo DDL and not the text. Ok, I realize I can just use the same field from the DS in the dataTextField as I'm using in the dataValueField, but that won't work for me...because when I'm calling create or update, I need to be able to pass the primary key or ID of that selected item back into my web api controller.
Here is the grids DS
function loadContactGrid(vendorID) {
var contactsReadURL = null;
contactsReadURL = "/contacts/getcontacts/" + parseInt(vendorID);
contactGridDS = new kendo.data.DataSource({
transport: {
read: {
url: contactsReadURL,
type: 'GET',
contentType: "application/json; charset=utf-8",
},
update: {
url: "/contacts/UpdateContacts/",
type: 'PUT',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(xhRequest, ErrorText, thrownError) {
alert('ERROR!!!\n' + ' xhRequest: ' + xhRequest + '\n' + ' ErrorText: ' + ErrorText + '\n' + ' thrownError: ' + thrownError + '\n');
},
complete: function(e) {
$("#contactGrid").data("kendoGrid").dataSource.read();
}
},
destroy: {
url: "/contacts/DeleteContact/",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "DELETE"
},
create: {
url: "/contacts/InsertContact/",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: "json",
success: function(results) {
alert('Contacts successfully saved!');
},
error: function(xhRequest, ErrorText, thrownError) {
alert('ERROR!!!\n' + ' xhRequest: ' + xhRequest + '\n' + ' ErrorText: ' + ErrorText + '\n' + ' thrownError: ' + thrownError + '\n');
},
complete: function(e) {
$("#contactGrid").data("kendoGrid").dataSource.read();
}
},
parameterMap: function(options, operation) {
if (operation !== "read" && options) {
return JSON.stringify(options.models);
}
if (operation == "create") {
// send the created data items as the "models" service parameter encoded in JSON
return { models: kendo.stringify(data.models) };
}
}
},
batch: true,
scrollable: false,
pageSize: 8,
change: function(e) {
if (e.action == "itemchange" && e.field == "email") {
var model = e.items[0];
if (isEmailValid($('input[name=email]').val()) == false) {
e.items[0].receivereport = false;
}
}
if (e.action == "itemchange" && e.field == "contacttype") {
var model = e.items[0];
//setTimeout(function () {
//$('.k-dirty-cell').focusout(function() {
//alert($(this).text(textOverrideContactType(e.items[0].contacttype)));
//});
//textOverrideContactType(e.items[0].contacttype);
//}, 1000); attempting to change text in cell here failed
}
if (e.action === "remove") {
this.sync();
}
},
schema: {
model: {
id: 'contactid',
fields: {
roletyp_seq: { editable: false, nullable: false, required: true, type: 'string' },
contacttype: { editable: true, nullable: false, required: true, type: 'number' },
roletyp_pk: { editable: false, nullable: false, required: true, type: 'number' },
contactid: { editable: false, nullable: false, required: true, type: 'number' },
vendorid: { editable: false, nullable: false, required: true, type: 'number' },
prevrole_pk: {
editable: false,
nullable: true,
required: true,
type: "number",
}
}
}
},
});
And my grid
$("#contactGrid").kendoGrid({
dataSource: contactGridDS,
navigatable: true,
dataBound: mapContactTypes,
editable: true,
//editable: "inline",
//editable: "popup",
edit: function (input) {
if ($('input[name=receivereport]').is(':focus')) {
//detect if email is valid
//get input immediately before this one
if (isEmailValid($('input[name=receivereport]').parent().prev().text()) == false) {
// disable check box
// alert("invalid");
$('input[name=receivereport]').attr('disabled', 'true');
$('input[name=receivereport]').prop('checked', false);
} else {
// enable check box
// alert("valid");
$('input[name=receivereport]').removeAttr('disabled');
$('input[name=receivereport]').prop('checked', false);
}
}
//when user clicks into or out of a field, if the name in the respective row name is blank, alert the user
var grid = this;
var fieldName = grid.columns[input.container.index()].field;
if (isNameInContactGridPopulated(fieldName) == false) {
alert("You can't leave out a contact name in the row you are editing.");
//disable save button
$('.k-grid-save-changes').addClass('k-state-disabled');
$('.k-grid-save-changes').hide();
} else {
//do nothing
$('.k-grid-save-changes').removeClass('k-state-disabled');
$('.k-grid-save-changes').show();
}
if ($('input[name=contactname]').is(":focus") == true) {
//disable save button
if ($('input[name=contactname]').val() == '') {
$('.k-grid-save-changes').addClass('k-state-disabled');
$('.k-grid-save-changes').hide();
}
}
$('input[name=contactname]').keyup(function() {
if ($(this).val() == '') {
$('.k-grid-save-changes').addClass('k-state-disabled');
$('.k-grid-save-changes').hide();
}
});
$('input[name=contactname]').focusout(function () {
if ($(this).val() != '') {
$('.k-grid-save-changes').removeClass('k-state-disabled');
$('.k-grid-save-changes').show();
}
});
},
toolbar: ["save", "cancel"],
pageable: true,
columns: [
{ field: 'roletyp_seq', title: 'RT Seq.', hidden: true, attributes: { 'class': 'contactCell_roletyp_seq' } },
{ field: 'contacttype', title: 'Contact Type', hidden: false, attributes: { 'class': 'contactCell_contacttype' }, editor: loadContactTypeEditor, width: "200px", template: "#=textOverrideContactType(1)#" },
//{ field: 'contacttype', title: 'Contact Type', hidden: false, attributes: { 'class': 'contactCell_contacttype' }, editor: loadContactTypeEditor, width: "200px", template: "#=textOverrideContactType(contacttype)#" },
//{ field: 'contacttype', title: 'Contact Type', hidden: false, attributes: { 'class': 'contactCell_contacttype' }, editor: loadContactTypeEditor, width: "200px" },
{ field: 'prevrole_pk', title: 'prev role ID', hidden: true, attributes: { 'class': 'contactCell_prevrole_pk' } },
{ field: 'roletyp_pk', title: 'Role Type ID', hidden: true, attributes: { 'class': 'contactCell_roletyp_pk' } },
{ field: 'contactid', title: 'Contact ID', hidden: true, attributes: { 'class': 'contactCell_contactid' } },
{ field: 'vendorid', title: 'Vendor ID', hidden: true, attributes: { "class": 'contactCell_vendorid' } },
{ field: 'contactname', title: 'Name', hidden: false, attributes: { "class": 'contactCell_contactname' } },
{ field: 'workphone', title: 'Phone', hidden: false, attributes: { "class": 'contactCell_phone' } },
{ field: 'mobilephone', title: 'Cell', hidden: false, attributes: { "class": 'contactCell_mobilephone' } },
{ field: 'title', title: 'Title', hidden: false, attributes: { "class": 'contactCell_title' } },
{ field: 'email', title: 'Email', hidden: false, attributes: { "class": 'contactCell_email' } },
{ field: 'receivereport', title: 'Receive Reports?', hidden: false, attributes: { "class": 'contactCell_receivereport' }, template: '<input type="checkbox" #= receivereport ? "checked=checked" : "" # value="" disabled="disabled" ></input>' },
{ command: "destroy", title: " ", width: "100px" }
],
sortable: {
mode: 'single',
allowUnsort: false
}
});
Then, I have two functions below. 1 is the custom editor and the other is an attempt I considered to override the text displayed in the kendo ddl.
function loadContactTypeEditor(container, options) {
var contactTypeDS = new kendo.data.DataSource({
dataType: "json",
type: "GET",
transport: {
read: "/contacts/GetAllContactTypes/"
}
});
contactTypeDS.read();
$('<input class="contactTypeDropDown" required data-text-field="roletyp_dsc" data-value-field="roletyp_pk" data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
dataTextField: "roletyp_dsc",
dataValueField: "roletyp_pk",
autoBind: false,
select: function (e) {
//if (e.sender.text() != '') {
// $('#contactGrid_active_cell').html(e.sender.text());
//}
//if (e.sender.text() != '') {
// setTimeout(function() {
// $('.contactCell_contacttype').text(e.sender.text());
// }, 1000);
//}
//options.model[options.field] = e.sender.text();
},
//dataBound: function(){
// options.model[options.field] = e.sender.text();
//},
dataSource: contactTypeDS
});
}
function textOverrideContactType(roleId) {
//need to find a match on the passed in role/contact type ID and return it's match to "mask/overwrite" the text that's there after a user selects an item in the dropdown
$.ajax({
dataType: 'json',
type: 'GET',
url: "/contacts/GetAllContactTypes/",
contentType: 'application/json; charset=utf-8',
success: function (data) {
$.each(data, function (key, val) {
if (roleId == key) {
return val;
}
});
},
failure: function (error) {
alert("Error loading contact types.");
}
});
}
To summarize: I tried a few things with no avail. What is happening, is, the DDL renders just fine, and even when the user doesn't move off of that DDL, the proper "label" shows, but when that control loses focus, it shows the data-value-field. I can't have that, I need to be able to show the data-text-field. That's why I wrote that textoverride method. But I'm trying to call it within the grid, fields's template: and it's not working. It says it doesn't recognize that function. I don't get it; it's clearly declared. What am I supposed to pass in as the parameter, it's not exactly like the demo here...a bit different, as I'm populating the DDL with another remote data source.
http://demos.telerik.com/kendo-ui/grid/editing-custom
Here's the other thing; I need that data-value-field, ID, to persist and be passed into my web api controller when it gets called. Right now, as it stands, I'm only able to get the "text" to show in the controller and not the "ID." That ID will not be available to me in the read method. The stored procs that the CRUD is hitting is completely different. My stored proc for insert and update needs to get that contacttype ID as the number.
Thanks in advance. I'm sure I'm close...
From the provided information it seems that you need to make the column ForegnKey by setting the "values" option of the column. Please check the example below:
[demo] Grid: ForeignKey column
[documentation] Grid API: columns.values option
I actually ended up using another means to do this. The above still seems illusive to me. I ended up changing the values of a key in another row, that was already available, to get passed back into the controller. I tried the answers provided with no avail. Sorry!

Kendo UI Inline grid not receiving Date Fields but other fields value getting in controller

I have used Kendo UI grid with inline editing, all filed received in controller but date field not receiving why?
This is my code, please help me
Grid---
$(document).ready(function() {
$("#orders-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("CustomerList", "Customer"))",
type: "POST",
dataType: "json",
},
create: {
url: "#Html.Raw(Url.Action("CustomerAdd", "Customer"))",
type: "POST",
dataType: "json"
},
update: {
url:"#Html.Raw(Url.Action("CustomerUpdate", "Customer"))",
type: "POST",
dataType: "json"
},
destroy: {
url: "#Html.Raw(Url.Action("CustomerDelete", "Customer"))",
type: "POST",
dataType: "json"
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
stfName: { editable: true, type: "string", validation: { required: true } },
Id: { editable: false, type: "number" },
stmName: { editable: true, type: "string", validation: { required: true } },
dtdob: { editable: true, type: "Date",format : "dd/MMM/yyyy", validation: { required: true } },
strefName: { editable: true, type: "string", validation: { required: true } },
}
}
},
requestEnd: function (e) {
if (e.type == "create" || e.type == "update") {
this.read();
}
},
error: function(e) {
//display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
pageSizes: [10]
}, //scrollable: false,
// dataBound: onDataBound,
sortable: true,
scrollable: {
virtual: true
},
toolbar: ["create"],
editable: {
confirmation: false,
mode: "inline"
},
columns: [
{
field: "Id",
title: "ID",
width: 50
},{
field: "stfName",
title: "First Name",
//attributes: { "class": "upper" },
width: 200
},
{
field: "dtdob",
title: "D.O.B.",
//editor: customDateEditor,
type: "Date",
template: "#=kendo.toString(dtdob,'dd/MMM/yyyy')#",
//template: '<input type="date" name="dtdob" />',
width: 200,
//parseFormats: ["yyyy-MM-dd'T'HH:mm:ss.zz"]
},
{
field: "strefName",
title: "Reference",
width: 200
},
{
command: [{
name: "edit",
text: "Edit"
}, {
name: "destroy",
text: "Delete"
}],
width: 200,
filterable: true
}]
});
var customDateEditor = function (container, options) {
$('<input />')
.appendTo(container)
.kendoDatePicker({
format: "dd/MMM/yyyy"
});
};
});
--model
public partial class tblCustomer
{
public int Id { get; set; }
public string stfName { get; set; }
public DateTime dtdob { get; set; }
}
}
Controller----
public ActionResult CustomerUpdate(tblCustomer model) <-All Value receive in model except date field dtdob
{
}
I have check in firebug there is ajax call and all fields pass properly event date too, but not receiving in controller why?
Regards,
Vinit Patel
Please go through the link given below. It does have couple of solutions for the issue you are fixing. Please revert if the issue persists.
Passing dates from Kendo UI to ASP.NET MVC

What is failing on my kendo cascading dropdownlist.Only works first time

So im currently using 2 dropdownlists where the second should get items from the server according to the selected item from the first one, the problem is that this only works the first timei click on the child droplist, which means if i change the parent list item the child one will still show the previous items.
Here's some code:
kendofi=function (index){
//kendofi select boxes
$("#dynamicFormLinha"+index).kendoDropDownList({
name:"formularios",
optionLabel: "Formulario",
dataTextField: "name",
dataValueField: "id",
dataSource: {
type: "json",
serverFiltering: true,
transport: {
read: "${pageContext.request.contextPath}" + "/newlayout/mySearchesDynForms.do"
},
schema: {
model: {
fields: {
id: { type: "number" },
name: { type: "string" }
}
}
}
}
}).data("kendoDropDownList");
$("#campoFormLinha"+index).kendoDropDownList({
autoBind:false,
name:"campos",
optionLabel: "Campo",
dataTextField: "name",
dataValueField: "id",
dataSource: {
type: "json",
serverFiltering:true,
transport: {
read:{
url:"${pageContext.request.contextPath}" + "/newlayout/mySearchesFormFieds.do",
data:function(){
return {formId: $("#dynamicFormLinha"+index).val()
};
}
}
}
},
cascadeFrom: "dynamicFormLinha1",
schema: {
model: {
fields: {
id: { type: "number" },
name: { type: "string" }
}
}
}
}).data("kendoDropDownList");
And here's the java spring controller class methods for each dropdownlist:
#RequestMapping(method = RequestMethod.GET, value="/newlayout/mySearchesDynForms")
public #ResponseBody
DynamicFormTemplateDPO[] getForms(){
return dynamicFormService.getAllActiveFormTemplatesForPresentation();
}
#RequestMapping(method = RequestMethod.GET, value="/newlayout/mySearchesFormFieds")
public #ResponseBody
DynamicFieldTemplateDPO[] getFormFields(#RequestParam long formId){
return dynamicFormService.getFormFields(formId);
}
These all return json data, the parent child returns this:
[{"id":1,"name":"drcie"},{"id":2,"name":"edp"},{"id":3,"name":"pt"}]
And the id selected is then used as the formId parameter in the getFormFields method, which returns something like this:
[{"id":1,"name":"Nome","type":"STRING"},{"id":2,"name":"Morada","type":"STRING"},{"id":3,"name":"Contribuinte","type":"STRING"},{"id":4,"name":"Multibanco","type":"STRING"}]
The kendofi method here is because these widgets are inside a table and you can add new table rows while maintaining the widgets functionality.
I had the same problem. We managed to solve this by putting the parent and children dropdownlists in one function. See buildLookupDropDownList() function below. Looks like in our situation the children dropdownlists were being called before the parent. Best of luck
var categories
function buildLookupDropDownList() {
categories = $("#LOOKUP_OBJECT_ID").kendoDropDownList({
optionLabel: "#Resources.Global.Builder_Parameter_SelLookup",
dataTextField: "OBJECT_NAME",
dataValueField: "OBJECT_ID",
dataSource: lookupDS,
}).data("kendoDropDownList");
var products = $("#DISPLAY_FIELD").kendoDropDownList({
autoBind: false,
cascadeFrom: "LOOKUP_OBJECT_ID",
optionLabel: "#Resources.Global.Builder_Parameter_SelDisplay",
dataTextField: "DISPLAY_LABEL",
dataValueField: "FIELD_NAME",
dataSource: {
serverFiltering: true,
transport: {
read:
{
url: '#Url.Action("GetFields", "Object")',
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: function () {
var lookuplist = $("#LOOKUP_OBJECT_ID").data("kendoDropDownList");
return { OBJECT_ID: lookuplist.value() };
}
}
},
schema: {
data: function (data) { //specify the array that contains the data
return data.data || data;
}
}
}
}).data("kendoDropDownList");
var orders = $("#VALUE_FIELD").kendoDropDownList({
autoBind: false,
cascadeFrom: "DISPLAY_FIELD",
optionLabel: "#Resources.Global.Builder_Parameter_SelValue",
dataTextField: "DISPLAY_LABEL",
dataValueField: "FIELD_NAME",
dataSource: {
serverFiltering: true,
transport: {
read:
{
url: '#Url.Action("GetFields", "Object")',
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: function () {
var lookuplist = $("#LOOKUP_OBJECT_ID").data("kendoDropDownList");
return { OBJECT_ID: lookuplist.value() };
}
}
},
schema: {
data: function (data) { //specify the array that contains the data
return data.data || data;
}
}
}
}).data("kendoDropDownList");
}

Kendo UI grid not calling the webservice

I am new to Kendo UI, I have a grid which I populate from a asmx webservice in JSON format, it displays the data fine. I have enabled editing, but when I click the update button nothing happens, I am not getting to the breakpoint in my webmethod.
Here is the relevant code snipets.
Thanks
//references
<link href="Content/kendo/2012.3.1114/kendo.common.min.css" rel="Stylesheet" />
<link href="Content/kendo/2012.3.1114/kendo.default.min.css" rel="Stylesheet" />
<script src="Scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script src="Scripts/kendo/2012.3.1114/kendo.web.min.js" type="text/javascript"></script>
//Data Model Classes
[Serializable]
public class Make
{
public int PhoneMakeID { get; set; }
public string PhoneMakeDesc { get; set; }
public string BillingDesc { get; set; }
}
//Web Methods
//Phone Make Get that populates the grid, works 100%
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Make> GetPhoneMakes(string Active, string OfferTypeID, string TrackMonthID, string NetworkID)
{
DataTable dtPhoneMakes = new DataTable();
Microsoft.Practices.EnterpriseLibrary.Data.Database db = DatabaseFactory.CreateDatabase("PricingConnection");
DbCommand dbCommand = null;
dbCommand = db.GetStoredProcCommand("uspPS_PhoneMake_Get");
db.AddInParameter(dbCommand, "#OfferTypeID", DbType.String, OfferTypeID);
db.AddInParameter(dbCommand, "#TrackMonthID", DbType.String, TrackMonthID);
db.AddInParameter(dbCommand, "#NetworkID", DbType.String, NetworkID);
db.AddInParameter(dbCommand, "#Active", DbType.String, Active);
dtPhoneMakes = db.ExecuteDataSet(dbCommand).Tables[0];
List<Make> ml = new List<Make>();
Make m;
foreach (DataRow dr in dtPhoneMakes.Rows)
{
m = new Make();
m.PhoneMakeID = Convert.ToInt32(dr["PhoneMakeID"].ToString());
m.PhoneMakeDesc = dr["PhoneMakeDesc"].ToString();
m.BillingDesc = dr["BillingDesc"].ToString();
ml.Add(m);
}
return ml;
}
//Phone Make Update, not getting to here
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void UpdatePhoneMakes(string PhoneMakeID, string PhoneMakeDesc, string BillingDesc)
{
Microsoft.Practices.EnterpriseLibrary.Data.Database db = DatabaseFactory.CreateDatabase("PricingConnection");
DbCommand dbCommand = null;
dbCommand = db.GetStoredProcCommand("uspPS_PhoneMake_Update");
db.AddInParameter(dbCommand, "#PhoneMakeID", DbType.String, PhoneMakeID);
db.AddInParameter(dbCommand, "#PhoneMakeDesc", DbType.String, PhoneMakeDesc);
db.AddInParameter(dbCommand, "#BillingDesc", DbType.String, BillingDesc);
db.ExecuteNonQuery(dbCommand);
}
//Transports
var transpPhoneMake = {
read: function (options) {
$.ajax({
type: "POST",
url: "webmethods/phones.asmx/GetPhoneMakes",
contentType: "application/json; charset=utf-8",
data: jdPhoneMake,
dataType: 'json',
success: function (msg) {
options.success(msg);
}
});
},
update: function (options) {
url: "webmethods/phones.asmx/UpdatePhoneMakes/";
contentType: "application/json; charset=utf-8";
type: "POST";
},
parameterMap: function (data, operation) {
if (operation != "read") {
return JSON.stringify({ products: data.models })
}
else {
data = $.extend({ sort: null, filter: null }, data);
return JSON.stringify(data);
}
}
};
//DataSources
var dsPhoneMake = new kendo.data.DataSource({
transport: transpPhoneMake,
schema:
{
data: "d",
total: "d.length",
model:
{
id: "PhoneMakeID",
fields:
{
PhoneMakeID: { type: "string", editable: false, nullable: true },
PhoneMakeDesc: { type: "string", editable: true },
BillingDesc: { type: "string", editable: true }
}
}
},
pageSize: 10,
sort:
{
field: "PhoneMakeDesc",
dir: "asc"
}
});
//Grids
var gridPhoneMakes = $("#gridPhoneMakes").kendoGrid({
dataSource: dsPhoneMake,
columns:
[
{ command: ["edit", "destroy"], title: " ", width: "175px" },
{
field: "PhoneMakeID",
title: "Make ID",
filterable: false,
editable: false,
width: 75
},
{
field: "PhoneMakeDesc",
title: "Make Description",
editable: true
},
{
field: "BillingDesc",
title: "Make Code",
editable: true
}
],
toolbar: kendo.template($("#tmplPhoneMakeToolbar").html()),
selectable: "row",
sortable: true,
groupable: true,
pageable: true,
filterable: true,
autoBind: false,
editable: "inline",
batch: false
});
Your transport definition says:
update: function (options) {
url: "webmethods/phones.asmx/UpdatePhoneMakes/";
contentType: "application/json; charset=utf-8";
type: "POST";
},
When you are actually not defining a function. It should be something like:
update: {
url: "webmethods/phones.asmx/UpdatePhoneMakes/",
contentType: "application/json; charset=utf-8",
type: "POST",
},
But all transport definitions must be consistent (Excerpt from KendoUI documentation)
Note: transport methods should be consistent - create, update and
destroy should be specified as functions too
(Thanks #LindsySimon for the remark)
You should do as you did for read:
read: function (options) {
$.ajax({
url: "webmethods/phones.asmx/UpdatePhoneMakes/",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (result) {
...
}
});
}

Resources