Kendo Ui Editor not sending FK on Create - ajax

Using the Kendo Grid with popup Create. Here is the code with datasource:
var PersId = $("#PersonId").val();
var ds_CommentsGrid = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("JsonGetComments", "TrespassOrder")/' + PersId,
dataType: 'json',
},
update: {
url: '#Url.Action("JsonEditComment", "TrespassOrder")',
dataType: 'json',
type: "POST"
},
create: {
url: '#Url.Action("JsonAddComment", "TrespassOrder")',
dataType: 'json',
type: "POST"
//contentType: 'application/json; charset=UTF-8',
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
var values = {};
values["CommentText"] = options.models[0].CommentText;
values["ModifiedBy"] = options.models[0].ModifiedBy;
values["ModifiedDate"] = options.models[0].ModifiedDate;
values["CreatedBy"] = options.models[0].CreatedBy;
values["CreatedDate"] = options.models[0].CreatedDate;
values["PersonId"] = options.models[0].PersonId;
return values;
}
}
},
batch: true,
schema: {
model: {
id: "CommentId",
fields: {
CommentText: { editable: true },
CreatedDate: { editable: false , type: "date"},
ModifiedDate: { editable: false , type: "date" },
CreatedBy: { editable: false },
ModifiedBy: { editable: false },
PersonId: { editable: false}
}
}
},
pageSize: 5
});
$(document).ready(function () {
$("#comment-list").kendoGrid({
dataSource: ds_CommentsGrid,
sortable: true,
filterable: { extra: false, operators: {
string: { startswith: "Starts with", eq: "Is equal to" }
}
},
pageable: true,
columns: [{
field: "CommentText", title: "Comment", width: 300, filterable: true
}, {
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: "Actions"
}],
editable: "popup",
toolbar: [{ name: "create", text: "Add New Comment" }]
});
});
There are 2 problems:
1. The PersonId is not being sent with the Create.
2. The dates are being sent in a format that ends up getting to the MVC controller as null (1/1/0001).
Here is what is being sent to the controller:
Request URL:http://localhost:47621/TrespassOrder/JsonAddComment
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:http://localhost:47621
Referer:http://localhost:47621/Person/Detail/18
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
CommentText:Blah blah, I am a comment.
ModifiedBy:
ModifiedDate:Fri Jun 14 2013 12:12:46 GMT-0700 (Pacific Daylight Time)
CreatedBy:
CreatedDate:Fri Jun 14 2013 12:12:46 GMT-0700 (Pacific Daylight Time)
PersonId:
Notice the PersonId is empty.
Notice the commented-out contentType in the create, within the transport. I tried using the json content type, but that returned an error saying that 'CommentText is an invalid JSON primitive".
So how do I format the dates so they show up in the controller, and how do I attach the foreign key (PersonId) to the data that is sent?

PersonId is set as not editable, it has not default value and there is no column definition. What do you expect to be sent on creation PersId? If so, you can defaultValue in the schema.model.fields.PersonId as PersId, something like:
schema : {
model: {
id : "CommentId",
fields: {
CommentText : { editable: true },
CreatedDate : { editable: false, type: "date"},
ModifiedDate: { editable: false, type: "date" },
CreatedBy : { editable: false },
ModifiedBy : { editable: false },
PersonId : { editable: false, defaultValue: PersId}
}
}
},
Regarding the format of the transmitted dates, they are transmitted as strings so you should convert them to a format that your controller is able to parse. For doing it, you should use kendo.toString (see this article about it). You might try using Universal sortable date/time, something like:
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
var values = {};
values["CommentText"] = options.models[0].CommentText;
values["ModifiedBy"] = options.models[0].ModifiedBy;
values["ModifiedDate"] = kendo.toString(options.models[0].ModifiedDate, "u");
values["CreatedBy"] = options.models[0].CreatedBy;
values["CreatedDate"] = kendo.toString(options.models[0].CreatedDate, "u");
values["PersonId"] = options.models[0].PersonId;
return values;
}
}

Related

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

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"
},

Kendo UI DataSource not triggering transport.destroy

I am using Kendo UI with ASP.NET Web API. There is a ProjectsController that has all the necessary methods.
My issue is that when I click on Delete button, Kendo UI grid will raise remove() event, but DataSource never invokes transport.destroy. Rather, it seems that tansport.create is being invoked. In transport.parameterMap I can see that the operation is create instead of destroy.
Here is a sample JavaScript code:
$(document).ready(function () {
var apiUrl = '/api/projects/';
var dataType = 'json';
var dataSource = new kendo.data.DataSource({
batch: true,
autoSync: false,
transport: {
read: {
url: apiUrl,
dataType: dataType,
type: "GET"
},
update: {
url: apiUrl,
dataType: dataType,
type: "PUT"
},
destroy: {
url: apiUrl,
type: "DELETE"
},
create: {
url: apiUrl,
contentType: "application/json;charset=utf-8",
dataType: dataType,
type: "POST"
},
parameterMap: function (data, operation) {
console.log("Operation: " + operation);
if (operation === "create" && data.models) {
for (var i in data.models) {
var model = data.models[i];
if (model.ProjectId === 0) {
return kendo.stringify(model);
}
}
} else if (operation === "destroy") {
console.log("Data.Models: " + data.models);
console.log("Data.id: " + data.ProjectId);
return { id: data.ProjectId };
}
return data;
}
},
schema: {
id: "ProjectId",
model: {
fields: {
ProjectId: { type: "number", editable: false, nullable: false, defaultValue: 0 },
ProjectName: { type: "string", validation: { required: true } },
Status: { type: "string", validation: { required: true } },
IsActive: { type: "boolean" }
}
}
},
pageSize: 10,
serverPaging: false,
serverFiltering: false,
serverSorting: false
});
$("#projectsGrid").kendoGrid({
dataSource: dataSource,
groupable: false,
sortable: true,
pageable: {
refresh: true,
pageSizes: true
},
pageSize: 10,
toolbar: ["create"],
editable: "popup",
columns: [
{ field: "ProjectId", width: 30, title: "ID" },
{ field: "ProjectName", width: 180, title: "Project" },
{ field: "Status", width: 90, title: "Status" },
{ field: "IsActive", width: 40, title: "Is Active", type: "boolean", template: '<input type="checkbox" #if (IsActive) {# checked="checked" #}# disabled="disabled" />' },
{ command: ["edit", "destroy"], title: "&nbsp", width: "80px" }
],
remove: function (e) {
console.log("Delete button clicked.");
console.log("Project ID: " + e.model.ProjectId);
//dataSource.remove(e.model);
//dataSource.sync();
}
});
});
Web API works fine when requests are issued via Fiddler, but Kendo UI Grid shows:
POST http://localhost:port/api/Projects
when it should be DELETE.
Thanks everyone in advance!
On your datasource, you have the batch flag set to true, this means the datasource will make the call only after you tell it to, e.g calling sync().
http://docs.kendoui.com/api/framework/datasource#configuration-batch
As well as
Make sure you have defined Id in the model, as OnaBai explained here Why does the KendoUI Grid Transport Create event gets raised multiple times, and even when the action is Update? , your id is outside the model, should be in :
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
}
}
if someone has defined the id in model as answered in above ,but dataSource not triggering transport.destroy yet ,below configuration could be helpful:
editable: {
..
mode: "inline", //or "popup
...
}
//or
editable: "inline" //or "popup"
http://www.telerik.com/forums/transport-destroy-of-grid-editor-is-not-working

Kendo Grid Edit - Dates not getting to controller

Using Kendo UI with MVC3.
Using the network tab on developer tool, I can see all the correct data is being sent, but when I hover over the model parameter that is coming into the controller method, the dates are all 1/1/0001. Here is some data:
Header info from network request tab (shows the correct data is going to the controller:
Accept:application/json, text/javascript, */*; q=0.01
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:http://localhost:47621
Referer:http://localhost:47621/NewOrder/Detail/18
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
CommentId:9
CommentText:blah blah random text.
IncidentId:7
ModifiedBy:admin
ModifiedDate:Thu Jun 06 2013 08:15:08 GMT-0700 (Pacific Daylight Time)
CreatedBy:admin
CreatedDate:Thu Jun 06 2013 08:15:08 GMT-0700 (Pacific Daylight Time)
kendo code:
var IncId = $("#IncidentId").val();
var ds_CommentsGrid = new kendo.data.DataSource({
transport: {
read : {
url : '#Url.Action("JsonGetComments", "TrespassOrder")/' + IncId,
dataType: 'json',
type : "POST"
},
update : {
url : '#Url.Action("JsonEditComment", "TrespassOrder")',
dataType: 'json',
type : "POST"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
var values = {};
values["CommentId"] = options.models[0].CommentId;
values["CommentText"] = options.models[0].CommentText;
values["IncidentId"] = options.models[0].IncidentId;
values["ModifiedBy"] = options.models[0].ModifiedBy;
values["ModifiedDate"] = options.models[0].ModifiedDate;
values["CreatedBy"] = options.models[0].CreatedBy;
values["CreatedDate"] = options.models[0].CreatedDate;
return values;
}
}
},
batch : true,
schema : {
model: {
id : "CommentId",
fields: {
CommentId : { editable: false },
CommentText : { editable: true },
CreatedDate : { editable: false, type: "date"},
ModifiedDate: { editable: false, type: "date" },
CreatedBy : { editable: false },
ModifiedBy : { editable: false }
}
}
},
pageSize : 5
});
$(document).ready(function () {
$("#Comment-List").kendoGrid({
dataSource: ds_CommentsGrid,
sortable : true,
filterable: { extra: false, operators: {
string: { startswith: "Starts with", eq: "Is equal to" }
}
},
pageable : true,
columns : [
{ field: "CommentText", title: "Comment", width: 300, 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: "Actions" }
],
editable : "popup"
});
});
I am wondering about the content type as noted in the request header, is it correct?
Try sending the response as json:
update: {
url : '#Url.Action("JsonEditComment", "TrespassOrder")',
dataType: 'json',
type : "POST",
contentType: "application/json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
var values = {};
values["CommentId"] = options.models[0].CommentId;
values["CommentText"] = options.models[0].CommentText;
values["IncidentId"] = options.models[0].IncidentId;
values["ModifiedBy"] = options.models[0].ModifiedBy;
values["ModifiedDate"] = options.models[0].ModifiedDate;
values["CreatedBy"] = options.models[0].CreatedBy;
values["CreatedDate"] = options.models[0].CreatedDate;
return JSON.stringify(values);
}
}
ASP.NET MVC can't parse the string representation of a JavaScript Date object. However it can parse it when it is serialized as JSON.

Resources