After I click on the Update button in Kendo Grid, the insert into the database works but this doesnt cause the grid to exit edit mode - ajax

Below is my grid.
If you look at the save: event, you'll notice an AJAX call.
This AJAX call IS firing, data IS being inserted into the database and I can even see the alert function going through. However, the grid does not exit edit mode for the row I'm inline editing. I'm not sure what's going on because the error message is terrible. I keep getting:
TypeError: Cannot read property 'data' of undefined [http://localhost/x/Scripts/kendo.web.min.js:13]
Here's the grid:
function directorsOrRecipients(e)
{
awardTitleId = e.data.AwardTitleId;
var detailRow = e.detailRow;
detailRow.find(".childTabstrip").kendoTabStrip({
animation: {
open: { effects: "fadeIn" }
}
});
detailRow.find(".directorsOrRecipients").kendoGrid({
reorderable: true,
resizable: true,
dataSource: {
transport: {
read: {
url: "http://localhost/x/api/Awards/directors/" + awardTitleId,
type: "GET"
},
},
schema: {
model: {
id: "AwardDirectorId",
fields: {
"AwardDirectorId": { editable: false, type: "number" },
"namefirstlast": { editable: true, type: "string" },
"directorsequence": { editable: true, type: "number", validation: { min: 1 } },
"isonballot": { editable: true, type: "string" },
"concatenation": { editable: true, type: "string" },
"MoreNames": { editable: true, type: "number", validation: { min: 0 } },
}
}
}
},
columns: [
{ field: "AwardDirectorId", title: "Award Director Id" },
{ field: "namefirstlast", title: "Name", editor: namesAutoComplete },
{ field: "directorsequence", title: "Director Sequence", format: "{0:n0}" },
{ field: "isonballot", title: "On ballot?", editor: onBallotDropDownEditor },
{ field: "concatenation", title: "Concatenation" },
{ field: "MoreNames", title: "More names?", format: "{0:n0}" },
{ command: ["edit"], title: " ", width: 100 }],
sortable: true,
sort: { field: "namefirstlast", dir: "desc" },
editable: "inline",
toolbar: [{ name: "create", text: "Add New Director/Recipient" }],
save: function(e)
{
debugger;
if (e.data != "undefined")
{
$.ajax({
url: "http://localhost/x/api/awards/directors",
type: "POST",
dataType: "json",
data: $.parseJSON(directorData)
}).done(function()
{
alert('done!');
});
}
}
});
function onBallotDropDownEditor(container, options)
{
var data = [
{ "onBallotId": 1, "onBallotDescription": "Yes" },
{ "onBallotId": 2, "onBallotDescription": "No" }];
$('<input required data-text-field="onBallotDescription" data-value-field="onBallotDescription" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: data
});
}
}

After Success in Ajax call try this,
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();

In controller update function return an object insted of empty Json, like this it worked for me
return Json(ModelState.IsValid ? new object() : ModelState.ToDataSourceResult());

Related

KendoUI populate dropdown

I am new to kendoUI and I need some assistance with getting the data that is returned from a function to populate into the dropdown. I am currently getting [object HTMLSelectElement] - you can see in the image attached. Any help is appreciated.
data is returned in function
dropdown is not showing the years returned
LoadAcceptedSubmissionsGrid: function (module) {
// Grid for "Accepted" tab
var isAccepted = "true";
gridAcceptedSubmissions = $("#gridAcceptedSubmissions").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
serverSorting: true,
serverFiltering: true,
allowUnsort: true,
transport: {
read: function (options) {
var strFilter = JSON.stringify(options.data.filter);
var strSort = JSON.stringify(options.data.sort);
var pageSize = options.data.pageSize === undefined && gridAcceptedSubmissions !== null ?
gridAcceptedSubmissions.dataSource.total() :
options.data.pageSize;
var acceptedSubmissionsUrl = commonUrl + "/Forms/Submissions/"
+ upacsSessionId + "/" + userId + "/" + form + "/" + isAccepted + "/"
+ options.data.page + "/" + pageSize + "/" + options.data.skip;
$.ajax({
type: "POST",
url: acceptedSubmissionsUrl,
xhrFields: {
withCredentials: true
},
data: {
filter: strFilter,
sort: strSort
},
success: function (response) {
options.success(response);
},
error: function (result) {
options.error(result);
}
});
}
},
pageSize: 10,
batch: false,
schema: {
total: function (response) {
return response.total;
},
data: function (response) {
return response.values;
},
model: {
id: "submissionId",
fields: {
state: { editable: false, type: "string", sort: "asc" },
fipsCode: { editable: false, type: "number", sort: "asc" },
year: { editable: false, type: "number", sort: "desc" },
name: { editable: false, type: "string" },
createdBy: { editable: false, type: "string" },
createdOn: { editable: false, type: "date" },
lastModifiedBy: { editable: false, type: "string" },
lastModifiedOn: { editable: false, type: "date" },
isEditable: { editable: false, type: "boolean" },
isReviewable: { editable: false, type: "boolean" }
}
}
}
},
groupable: false,
sortable: {
showIndexes: true,
mode: "multiple"
},
resizable: true,
selectable: "row",
scrollable: true,
filterable: true,
navigatable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 10
},
dataBound: this.GridDataBound,
columns: [
{
field: "submissionId",
title: "Id",
},
{
field: "state",
title: "State",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("state", "name", true)
},
sort: "ascending"
},
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("year", null, true)
},
sort: "descending"
},
{
field: "status",
title: "Status",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("status", null, true)
}
},
{
field: "createdBy",
title: "Initiated By",
filterable: {
ui: this.FormCreatedByAcceptedFilter
}
},
{
field: "createdOn",
title: "Initiated On",
format: "{0:g}",
},
{
field: "lastModifiedBy",
title: "Modified By",
filterable: {
ui: this.FormLastModifiedByAcceptedFilter
}
},
{
field: "lastModifiedOn",
title: "Modified On",
format: "{0:g}"
},
{
title: "Action",
headerTemplate: "<div class='headerTemplate'><span class='headerText'>Action</span>" +
"<button class='clearAllFilters' id='clearAllFiltersAcceptedSubmissions' tabindex=0> Clear All Filters</button></div>",
command: [
{
name: "View",
text: " ",
visible: function (dataItem) { return !dataItem.isEditable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-View' title='View Form' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-eye'><span class='sr-only'>View form</span></i></a>";
return tmpl;
},
click: function (e) {
e.preventDefault();
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-existing-form", module);
}
},
{
name: "View History",
text: " ",
visible: function (dataItem) { return !dataItem.isReviewable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-ViewHistory' title='View Form History' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-history'><span class='sr-only'>View form history</span></i></a> ";
return tmpl;
},
click: function (e) {
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-status-history", module);
}
}
],
},
]
}).data("kendoGrid");
gridAcceptedSubmissions.hideColumn(0);
$("#clearAllFiltersAcceptedSubmissions").click(function () {
gridAcceptedSubmissions.dataSource.filter({});
});
},
Without seeing what BuildMultiCheckboxDataSource is doing, I can only make assumptions.
However, since you have declared year as an IEnumerable<int> then the datasource does not need to be anything elaborate. Simply set it to the collection being returned by the server:
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/my-endpoint-to-fetch-years-here"
}
}
})
},
sort: "descending"
}

How to get value id from dataSource by row Kendo UI Grid

Help me code How to get value id from dataSource by row and change to current value default (1)
in line: var date = dataSource.get(1);
console.log(date.ProductName)
My full source:
<div id="grid"></div>
<script>
$(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,
selectable: true,
pageable: true,
height: 550,
toolbar: ["create"],
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "120px" },
{ field: "UnitsInStock", title:"Units In Stock", width: "120px" },
{ field: "Discontinued", width: "120px", editor: customBoolEditor },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "inline",
edit: function () {
var date = dataSource.get(1);
console.log(date.ProductName)
}
});
});
</script>
Now, when click edit, all rows only get fields of id 1. I want corresponding id instead of the default id 1.
edit
Fired when the user edits or creates a data item.
The event handler function context (available via the this keyword)
will be set to the widget instance.
EVENT DATA
e.container jQuery The jQuery object of the edit container
element, which wraps the editing UI. Depending on the Grid edit mode,
the container is different:
"incell" edit mode - the container element is a table cell
"inline" edit mode - the container is a table row
"popup" edit mode - the container is a Kendo UI Window element, which provides an easy way to obtain a reference to the Window widget object, e.g. to attach additional events.
e.model kendo.data.Model The data item which is
going to be edited. Use its isNew method to check if the data item is
new (created) or not (edited).
e.sender kendo.ui.Grid The widget instance which fired the event.
$("#grid").kendoGrid({
columns: [
{ field: "id" },
{ field: "name" },
{ field: "age" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: {
id: "id",
fields: {
"id": { type: "number" }
}
}
}
},
editable: "popup",
toolbar:["create"],
edit: function(e) {
console.log(e.model.id);
console.log(e.model.name);
}
});
Working example: edit event
Documentation: grid edit event

kendo grid server re filtering the data source

$(document).ready(function () {
var agenciesData = new kendo.DataToken.DataSource({
type: 'webapi',
transport: {
read: { url: "/api/Agencies/", dataType: "json", data: { activity: getActivity() } },
create: { url: "/api/Agencies", type: "POST", dataType: "json" },
destroy: { url: "/api/Agencies/{0}", type: "DELETE" },
update: { url: "/api/Agencies/{0}", type: "PUT" },
idField: "ID"
},
filter: [{ field: "Activity", operator: "eq", value: getActivity() }],
pageSize: 15,
page: 1,
total: 0,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
schema: {
data: "Data",
total: "Total",
model: {
id: "ID",
fields: {
ID: { editable: false, type: "number" },
AgencyName: { type: "string" },
AgentName: { type: "string" },
Address: { type: "string" },
City: { type: "string" },
Tel1: { type: "string" },
Tel2: { type: "string" },
Pele: { type: "string" },
Activity: { type: "number" },
ToDate: { type: "date" }
}
}
}
});
$("#agenciesGrid").kendoGrid({
dataSource: agenciesData,
toolbar: [{ text: "valid", className: "validAgents" }, { text: "not valid", className: "notValid" }, { text: "all", className: "allAgents" }, { text: "potential", className: "potetial" }],
editable: false,
navigatable: true,
sortable: true,
autoBind: false,
height: 430,
pageable: { refresh: true },
columns: [
{ field: "ID", hidden: true },
{ field: "AgencyName", title: "agency", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "AgentName", title: "agent", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "Address", title: "address", width: 200, template: "#= Address + ' ' + City #", filterable: false },
{ field: "Tel1", title: "phones", width: 300, template: "#= Tel1 + ' : ' + Tel2 + ' : ' + Pele #", filterable: false },
{ field: "Activity", title: "active", width: "90px" },
{ field: "ToDate", title: "end Contract", type: "date", width: 90, format: "{0:dd/MM/yyyy}", parseFormats: ["yyyy-MM-ddThh:mm:ss"] }
]
});
$(".validAgents").click(function () { //valid
$("#myActivity").val("1");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "1" });
});
$(".notValid").click(function () {//notValid
$("#myActivity").val("2");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "2" });
});
$(".potetial").click(function () {//potetial
$("#myActivity").val("3");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "3" });
});
});
function getActivity(){
var myActivity = $("#myActivity").val();
return myActivity;
}
When I use kendo grid already filtered by parameter like : $('#someGrid').data().kendoGrid.dataSource.read({ activity: value });
i see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=&activity=1
The grid is filter as expected but, when I want to do paging, sorting, refresh - I get the whole data ignoring the filter that i made.
and I see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=
How can I save my filter state to do paging and sorting on the data came from the server side ?
even when i used differen approach like "scrollable: { virtual: true }" and when i scroll down - every request is without the filtering...
Thanks
Did you try
var agenciesData = new kendo.DataToken.DataSource({
filter : function () {
return object;
}
});
I mean try using filter as a function and you can do your logic inside the function depending on the situation.

Passing KENDO Grid data view to MVC controller

I have an issue sending Telerik Kendo Grid viewdata to MVC Controller. I've tried to make ViewModel etc but i just can't figure this one out.
Here is my code to populate grid:
var grid = $("#grid").kendoGrid({
dataSource: {
data: kontdata.Data,
schema: {
model: {
fields: {
Id: { type: "number", editable: false },
Name: { type: "string" },
Number: { type: "string" },
Info: { type: "string" },
Email: { type: "string" },
Category: { type: "string" },
MarketingAllowed: { type: "number", editable: false },
AddedDate: { type: "date", editable: false }
}
}
},
pageSize: 20
},
height: 500,
scrollable: true,
toolbar: kendo.template($("#template").html()),
serveroperation: false,
sortable: true,
editable: { mode: "incell", confirmation: false },
selectable: "row",
filterable: true,
pageable: true,
columns: [
{
field: "Name",
title: "Nimi"
},
{
field: "Number",
title: "Numero"
},
{
field: "Info",
title: "Info"
},
{
field: "Email",
title: "Email"
},
{
field: "Category",
title: "Kategoria"
},
{
field: "MarketingAllowed",
title: "Markkinointikielto",
width: "160px"
},
{
field: "AddedDate",
title: "LisÀttyPvm",
format: "{0:dd/MM/yyyy HH:mm:ss}"
},
{
command: [
{ name: "destroy", text: "Poista", width: "70px" }
]
}
]
}).data("kendoGrid");
And here is the code to post grid view data:
function tallennagridi() {
var griddata = $("#grid").data("kendoGrid");
$.ajax(
{
type: 'POST',
url: '/Contactlist/Savegriditems/',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ griditems: griddata.dataSource.view() }),
success: function (result) {
alert('success');
}
});
};
And here is the controller:
public JsonResult Savegriditems([DataSourceRequest] DataSourceRequest request, CustomerViewModel griditems)
{
var joku = griditems;
return Json(joku, "Content-type: text/x-json; charset=utf-8", JsonRequestBehavior.AllowGet);
}
Any help would be appreciated.
Br. Eero
My mistake, CustomerViewModel gridItems should have been:
CustomerViewModel[] gridItems;

Kendo grid - Posted Edit is null at Controller

Using kendo grid with Popup edit. I verified the data is posted from the view (I can see it in the Network Tab, here is a look at it:
{"LetterId":12,"BodyText":"This is a test","CreatedDate":"07/31/2013","CreatedBy":"Grace Rodgers","ModifiedDate":"07/31/2013","ModifiedBy":"Grace Rodgers","PersonId":18,"FirstName":"Jason","LastName":"Bigby"}:
However, I have a breakpoint at the json method in the controller, and when hovering over the model parameter, in shows all fields are null. Here is the first couple lines of the controller code:
[HttpPost]
public JsonResult JsonEditLetter(LetterViewModel model)
{
and the kendo code in the view:
var PersId = $("#PersonId").val();
var ds_LettersGrid = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("JsonGetLetterList", "Letter")/' + PersId,
dataType: 'json'
},
update: {
url: '#Url.Action("JsonEditLetter", "Letter")',
dataType: 'json',
type: "POST"
},
parameterMap: function (data, type) {
if (type == "update") {
data.models[0].CreatedDate = kendo.toString(new Date(data.models[0].CreatedDate), "MM/dd/yyyy");
data.models[0].ModifiedDate = kendo.toString(new Date(data.models[0].ModifiedDate), "MM/dd/yyyy");
return kendo.stringify(data.models[0]);
}
},
},
batch: true,
schema: {
model: {
id: "LetterId",
fields: {
BodyText: { editable: true },
CreatedDate: { editable: false, type: "date"},
ModifiedDate: { editable: false, type: "date" },
CreatedBy: { editable: false},
ModifiedBy: { editable: false },
PersonId: { defaultValue: PersId }
}
}
},
pageSize: 10
});
$(document).ready(function () {
$("#letter-list").kendoGrid({
dataSource: ds_LettersGrid,
sortable: true,
filterable: { extra: false, operators: {
string: { startswith: "Starts with", eq: "Is equal to" }
}
},
pageable: true,
columns: [{
field: "BodyText", title: "Letter Content", width: 400, filterable: false
}, {
field: "CreatedBy", title: "Author", filterable: false
}, {
field: "CreatedDate", title: "Original Date", format: "{0:g}", filterable: { ui: "datetimepicker" }
}, {
field: "ModifiedBy", title: "Edited By", filterable: false
}, {
field: "ModifiedDate", title: "Editted On", format: "{0:g}", filterable: { ui: "datetimepicker" }
}, {
command: [ "edit" ], title: "", width: "110px"
}],
height: "300px",
resizable: true,
editable: "popup"
});
});
You need to add default value to your id field , becouse the client side generates new id value, what you already have in server autoincrement generated id value and its shooting error
schema: {
model: {
id: "LetterId",
fields: {
LetterId: {defaultValue: 16000}
BodyText: { editable: true },
CreatedDate: { editable: false, type: "date"},
ModifiedDate: { editable: false, type: "date" },
CreatedBy: { editable: false},
ModifiedBy: { editable: false },
PersonId: { defaultValue: PersId }
}
}
}
I figured it out, it wanted a specific content type. The type being passed was a form, but the controller wanted json. So the Transport now looks like:
update: {
url: '#Url.Action("JsonEditLetter", "Letter")',
dataType: 'json',
>>>>>>>> contentType: "application/json",
type: "POST"
},

Resources