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.
Related
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
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
Uncaught TypeError: Cannot read property 'template' of undefined
I am using a kendo grid .
I want to Disable a Column when I edit.(Not when I add a new record).Did write code when edit
function onEdit(e) {
var indexCell = 1;
var grid = $('#consumablesGrid').data('kendoGrid');
if (e.model.id) { // when Editing the id is defined
if (indexCell != 'undefined' && grid.columns[indexCell].title == "Consumable") {
grid.closeCell();
}
}
}
But it shows "Uncaught TypeError: Cannot read property 'template' of undefined " when executing grid.closeCell() .
For better understanding I am Including My full grid Condition.
function ConsumableManager() {
$("#consumablesGrid").kendoGrid({
dataSource: {
transport: {
read: {
url: "GetConsumablesGrid",
type: "POST",
contentType: "application/json",
dataType: "json"
},
update: {
url: "UpdateConsumables",
contentType: "application/json",
type: "POST",
dataType: "json",
complete: function (data) {
var result = jQuery.parseJSON(data.responseText);
if (result.State == true) {
toastr.success(result.Description);
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
else {
toastr.error(result.Description);
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
}
},
destroy: {
url: "DestroyConsumables",
contentType: "application/json",
type: "POST",
dataType: "json",
complete: function (data) {
var result = jQuery.parseJSON(data.responseText);
if (result.State == true) {
toastr.success(result.Description);
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
else {
toastr.error(result.Description);
}
}
},
create: {
url: "CreateConsumables",
contentType: "application/json",
type: "POST",
dataType: "json",
complete: function (data) {
var result = jQuery.parseJSON(data.responseText);
if (result.State == true) {
toastr.success(result.Description);
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
else {
toastr.error(result.Description);
}
}
},
parameterMap: function (data, operation) {
if (operation != "read") {
return kendo.stringify(data.models);
}
}
},
serverPaging: false,
pageSize: 10,
batch: true,
schema: {
model: {
id: "ConsumablesID",
fields: {
ConsumablesID: { editable: false },
Consumable: { editable: true },
UnitCost: { editable: true },
Currency: { editable: true },
ContractID: { editable: false }
}
},
errors: "Errors"
},
error: function (e) {
alert(e.errors + "grid");
}
},
editable:
{
mode: "inline",
createAt: "bottom"
},
pageable: {
refresh: true,
pageSizes: true
},
toolbar: ["create"],
sortable: true,
autoBind: false,
edit: function (e) {
alert("Edit");
onEdit(e);
},
update: function (e) {
},
columns:
[
{ field: "ConsumablesID", width: 50, hidden: true, title: "ID" },
{ field: "Consumable", width: 200, title: "Consumable", editor: ConsumablesDropDownEditor },
{ field: "UnitCost", width: 100, title: "Unit Cost" },
{ field: "Currency", width: 200, title: "Currency", editor: CurrencyUnitDropDownEditor },
{ field: "ContractID", width: 85, hidden: true, title: "ContractID" },
{ command: ["edit", "destroy"], title: "Action", width: "175px" }
]
});
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
Anyone have Idea Why this happened.How can I do that Please response.
1.I've a grid
2.I want to editable (False) when edit (Not in add)
You probably have too new a jquery version: http://docs.telerik.com/kendo-ui/getting-started/javascript-dependencies#jquery-version
Current Kendo UI supports jquery 1.9.1. If you use later versions of jquery with kendo you may face issue with closeCell().
To fix(work around) this issue you can use
$('#consumablesGrid').getKendoGrid().trigger('cancel')
instead of grid.closeCell()
It's depend of jquery versions .
To avoid this problem you can use this script
function onEdit(e) {
if (!e.model.isNew() && (e.model != 'undefined') && (e.model != null)) {
e.container.find("input[name=GroupName]").hide(); // To hide only the value of the column when updating the row
// e.container.find("#GroupName").parent().hide().prev().hide(); //to hide completely the column (value + structure + title name)
}
}
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"
},
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;
}
}