Custom validations does not work in kendo ui grid update - validation

here is my code......
In here I try to add custom validation to update.
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "//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,
productnamevalidation: function (input) {
if (input.is("[name='ProductName']") && input.val() != "") {
input.attr("data-productnamevalidation-msg", "Product Name should start with capital letter");
return /^[A-Z]/.test(input.val());
}
return true;
}
}
},
UnitPrice: { type: "number", validation: { required: true, min: 1} },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { unitValidations : function(input){
if ((input.val() <= 1000) && (input.val() >= 10)) {
input.attr("data-max-msg","value must in given range");
input.attr("data-min-msg","value must in given range");
return true;
} else {
return false;
} }, required: true} }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
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" },
{ command: ["edit", "destroy"], title: " ", width: "250px"}],
editable: "inline"
});
});
</script>
</div>
In here you can see I added custom validation for update field....
UnitsInStock: { type: "number", validation: { unitValidations : function(input){
if ((input.val() <= 1000) && (input.val() >= 10)) {
input.attr("data-max-msg","value must in given range");
input.attr("data-min-msg","value must in given range");
return true;
} else {
return false;
} }, required: true} }
But it is not working fine. What should I change ??
you can run this from here

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

Kendo UI posting null values to paramter in web api controller method

I am using the following code in cshtml,
Controller display null value in parameter,
I require values to be populated in controller method parameter,
Please help
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var crudServiceBaseUrl = "http://localhost:49885/api",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Suppliers",
dataType: "json",
type: "Get"
},
update: {
url: function(data) {
debugger;
//return crudServiceBaseUrl + "/Suppliers/" + JSON.stringify(data.models[0]);
return crudServiceBaseUrl + "/Suppliers";
},
dataType: "json",
type: "Put",
contentType: "application/json"
},
destroy: {
url: function(data) {
debugger;
return crudServiceBaseUrl + "/Suppliers/" + JSON.stringify(data.SupplierId);
//return crudServiceBaseUrl + "/Suppliers";
},
//url: crudServiceBaseUrl + "/Suppliers",
dataType: "json",
type: "Delete",
contentType: "application/json"
},
create: {
url: function (data) {
debugger;
//return crudServiceBaseUrl + "/Suppliers/" + JSON.stringify(data);
return crudServiceBaseUrl + "/Suppliers";
},
//url: crudServiceBaseUrl + "/Suppliers",
dataType: "json",
type: "Post",
contentType: "application/json",
//data: JSON.stringify([data.SupplierId, data.CommId])
},
parameterMap: function(options, operation) {
debugger;
if (operation !== "read" && options) {
return { models: JSON.stringify(options) };
}
}
},
batch: false,
pageSize: 20,
schema: {
data: function(data) { //specify the array that contains the data
return data || [];
},
errors: function(response) {
return response.error;
},
model: {
id: "SupplierId",
fields: {
SupplierId: { validation: { required: true } },
CommId: { validation: { required: true } },
EmailId: { validation: { required: true } },
FullName: { validation: { required: true } },
FirstName: { validation: { required: true } },
Description: { validation: { required: true } },
LastName: { validation: { required: true } },
StateId: { validation: { required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
sortable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"SupplierId",
{ field: "SupplierId", title: "SupplierId", width: 120 },
{ field: "CommId", title: "CommId", width: 120 },
{ field: "EmailId", title: "EmailId", width: 120 },
{ field: "FullName", width: 120 },
{ field: "FirstName", width: 120 },
{ field: "Description", width: 120 },
{ field: "LastName", width: 120 },
{ field: "StateId", width: 120 },
{ command: "destroy", title: " ", width: 150 }
],
editable: true
});
});
</script>
<div id="example">
<div id="grid"></div>
</div>

Kendo Grid Showing error "Uncaught TypeError: Cannot read property 'template' of undefined "

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

Giving a unique ID on create new row for the kendo grid in the JS

I have a kendo grid.. It works fine.. But when I create a new row in the grid I need to provide a unique ID (integer is fine but not a duplicate one eg. 0, 1, 2, 3.. ) to save. At the moment when I get data from backend I count the number of rows and keep it in the session. And when an user requests for new row, I read the session and find the number of rows there and add 1 to create a unique ID. Is there any elegant way of giving a unique ID for the grid in the JS without using the session. Thanks in advance.
$("#TrainingDetailsGrid").kendoGrid({
dataSource: {
transport: {
read: {
url: "GetTrainingDetailsData",
datatype: "json",
type: "POST",
contentType: "application/json"
},
create: {
url: "UpdateTrainingDetailsData",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
update: {
url: "UpdateTrainingDetailsData",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation != "read") {
return kendo.stringify(data.models);
}
}
},
pageSize: 5,
serverPaging: false,
batch: true,
schema: {
model: {
id: "ID",
fields: {
ID: { editable: false },
Description: { editable: true, nullable: false, validation: { required: true } },
Instructor: { editable: true, nullable: false, validation: { required: { message: "Instructor name is required" } } },
Trainee: { editable: true },
TimeSpent: { editable: true, type: "number", validation: { required: { message: "Hours are required" }, min: 0, step: 0.25 } },
}
},
errors: "Errors"
},
error: function (e) {
alert(e.errors + "TrainingDetailsGrid");
}
},
groupable: false,
autoBind: false,
sortable: true,
toolbar: ["create"],
editable: "inline",
pageable: {
refresh: true,
pageSizes: true
},
dataBound: onDataBound,
columns:
[
{ field: "Description", width: 90, title: "Description" },
{ field: "Instructor", width: 90, title: "Instructor" },
{ field: "Trainee", width: 90, title: "Trainee" },
{ field: "TimeSpent", width: 90, title: "Hours" },
{ command: ["edit"], title: "Action", width: "175px" }
]
});
In your parameterMap you can count the number of rows you have in the Grid and put the value in the model before you pass it to the server side.
parameterMap: function (data, operation)
{
if (operation != "read") {
if (operation == "create") {
if ($("#TrainingDetailsGrid").data("kendoGrid").dataSource.total() > 0) {
data.models[0].ID = $("#TrainingDetailsGrid").data("kendoGrid").dataSource.total() - 1;
}
else {
data.models[0].ID = 0;
}
}
return kendo.stringify(data.models);
}
}

Kendo grid post and delete send null to controller

I'm posting a kendoui web grid and it isn't sending data and I can't see what I'm doing different from the sample that's failing. I'm posting to the controller, but it's either empty (if batch: true or null if batch: false)
var crudServiceBaseUrl = "api/Certifications/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + member.id,
dataType: "json"
},
update: {
url: crudServiceBaseUrl,
type: "Post",
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl,
type: "Delete",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
create: {
url: crudServiceBaseUrl,
type: "Post",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
editable: { //disables the deletion functionality
update: true,
destroy: true
},
batch: true,
pageSize: 30,
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, nullable: true },
MemberId: { editable: false, nullable: true },
Name: { validation: { required: true} },
AuthorityName: { validation: { required: true} },
StartDate: { type: "date", validation: { required: true} },
EndDate: { type: "date" }
}
}
}
});
$("#certifications").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 300,
toolbar: ["create"],
columns: [
{ field: "Name", title: "Product Name", width: 250 },
{ field: "AuthorityName", title: "Authority", format: "{0:c}", width: "140px" },
{ field: "StartDate", title: "Earned", template: '#= kendo.toString(StartDate,"MM/dd/yyyy") #', width: 50 },
{ field: "EndDate", title: "Expired", template: '#= kendo.toString(EndDate,"MM/dd/yyyy") #', width: 50 },
{ command: ["edit", "destroy"], title: " ", width: "130px" }],
editable: "popup"
});
the web api:
public Certification DeleteCertification(CertificationVm cert)
{
var model = Uow.Certifications.Get(cert.Id);
if (model == null)
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NoContent));
Uow.Certifications.Delete(model);
Uow.Commit();
return model;
}
I'd figured it out, although I had to depart from the example http://demos.kendoui.com/web/grid/editing-popup.html
The fix was add the content type, correctly use dataType: "json" as noted above, change from batch: true to batch: false and change the parameter map to the below
destroy: {
url: crudServiceBaseUrl,
type: "Delete",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
parameterMap: function (model, operation) {
if (operation !== "read" && model) {
return kendo.stringify(model) ;
}
}
There is no such thing as jsonp + POST - it is discussed here.
Do not use jsonp unless you really know why you need it.

Resources