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

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>

Related

Why can't I update or delete the new import of excel data in kendo grid?

I import the Excel file to server and the server return the JSON data to client. but after the new JSON data binding to the kendo grid dataSource, I can't update or delete this or these datas? What can I do to resolve this problem?
This is the form submit js code:
var form = $('#idForm');
var grid = $('#demo2').data('kendoGrid');
form.submit(function (e) {
var formData = new FormData($(this)[0]);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: formData,
cache: false,
processData: false,
contentType: false,
dataType: 'json',
//async: false,
success: function (response) {
if (response.result) {
***grid.dataSource.data(response.data);***
$('#moneyin').text(response.context.moneyin);
$('#moneyout').text(response.context.moneyout);
$('#moneyleft').text(response.context.moneyleft);
} else {
alert(response.message);
}
},
error: function (response) {
alert("error");
}
});
//e.preventDefault(); // avoid to execute the actual submit of the form.
return false;
});
var url = site_url + 'inline_edit/';
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: site_url + 'initial/',
type: 'GET',
dataType: "json"
},
update: {
url: url,
type: 'POST',
dataType: 'json'
},
create: {
url: url,
type: 'POST',
dataType: 'json'
},
destroy: {
url: url,
type: 'POST',
dataType: 'json'
},
parameterMap: function (options, operation) {
//if (operation == "read") {
// return {
// page: options.page,
// pageSize: options.pageSize,
// start: $('#start').val(),
// end: $('#end').val()
// }
//}
if (operation !== "read" && options.models) {
for (var k = 0; k < options.models.length; k++) {
var date_str = date2str(options.models[k].date, 'yyyy-MM-dd');
var recor_str = date2str(new Date(), 'yyyy-MM-dd');
options.models[k].date = date_str;
options.models[k].recordate = recor_str;
}
return {
'operation': operation,
'models': kendo.stringify(options.models)
};
}
}
},
requestEnd: function (e) {
if (e.response && e.response.context) {
$('#moneyin').text(e.response.context.moneyin);
$('#moneyout').text(e.response.context.moneyout);
$('#moneyleft').text(e.response.context.moneyleft);
}
},
//serverPaging: true,
batch: true,
pageSize: 7,
schema: {
model: {
id: 'id',
//data type of the field {Number|String|Boolean|Date|datetime} default is String
fields: {
id: {
type: "number",
editable: false,
nullable: false
},
date: {
type: "date",
defaultValue: new Date(),
validation: {
required: true
}
},
fundbefore: {
type: "number",
editable: false,
nullable: true
},
moneyin: {
type: "number",
validation: {
min: 0,
required: true
}
},
moneyout: {
type: "number",
validation: {
min: 0,
required: true
}
},
fundafter: {
type: "number",
editable: false,
nullable: true
},
charge: {
type: "string",
validation: {
required: true
}
},
reason: {
type: 'textarea',
validation: {
required: true
}
},
recordate: {
type: 'date',
editable: false,
defaultValue: new Date()
},
modify: {
editable: false,
defaultValue: user_name
}
}
},
data: function (response) {
if (response.result) {
return response.data;
} else {
return alert(response.message);
}
},
total: function (response) {
return response.total;
}
}

Custom validations does not work in kendo ui grid update

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

How I write a dynamic URL in kendo UI DataSource like "update/{id}"

I have a web API. In that I wrote a update method. But it need to id of the table row to update to the row.
I use a grid to show data and use a toolbar to edit the row.
My question is how I pass that id to the update.
Can someone guide me ??
update: function(options) {
$.ajax( {
url: function(data) { return "updateUsuarios/"+data.Id,
dataType: "json",
.....
Well i suggest you, explain more your question, but i think this examples could help , if you have a toolbar as a template like this:
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<button type="button" id="update">Update</button>
</div>
</script>
You "grid" need the attr "toolbar"
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
filterable:true,
toolbar: kendo.template($("#template").html()),
columns: [
{ field:"username", title: "Username" , width: "120px" },
{ field: "nombre", title:"Nombre", width: "120px" },
{ field: "apellido", title:"Apellido", width: "120px" },
{ field: "ci", title:"Documento de Identidad", width: "120px" },
{ field: "email", title:"Direccion de Correo", width: "120px" },
{ field: "activo",title:"Estatus", width: "120px" },
{ field: "fecha_caducidad",title:"Fin Demo", width: "120px",template: "#= kendo.toString(kendo.parseDate(fecha_caducidad, 'yyyy-MM-dd'), 'MM/dd/yyyy') #" },
{ field: "licencia_status",title:" ", width: "40px",template:'<img src="assets/images/#:data.licencia_status#.png"/>' },
{ command: ["edit"], title: " ", width: "120px" }],
editable: "popup",
dataBound: function () {
var rows = this.items();
$(rows).each(function () {
var index = $(this).index() + 1;
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
},
selectable: true
});
So,you can configure a kendo button and add functionality in the event click:
$("#update").kendoButton({
click: function(){
//Here you will have the selected row
var self=$('#grid').data('kendoGrid')
var index = self.items().index(self.select());
var rowActual= self.dataSource.data()[index];
rowActual=self.dataItem(self.select());
if(rowActual==undefined || rowActual ==null) {
alert("No row selected");
}else{
$.ajax({
type: "POST",
url: "update",
data: {
id:rowActual.id
},
dataType: 'json',
success: function (data) {
},
error: function(){
}
});
}
}
});
and send in the ajax the row id, but if you are update the row with the inline edition you could try with a datasource like this
dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: "readUsuarios",
dataType: "json",
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
$.ajax( {
url: "updateUsuarios",
dataType: "json",
data: {
models: kendo.stringify(options.data.models)
},
success: function(data) {
// response server;
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "id",
fields: {
username: { editable: false, nullable: true },
nombre: { validation: { required: true } },
apellido: { type: "string", validation: { required: true} },
ci: { type: "string", validation: { required: true} },
email: { type: "string", validation: { required: true } },
activo: { type: "boolean",editable: false },
fecha_caducidad: { type: "date" },
licencia_status:{editable: false}
}
}
}
});
I hope this help!

InCell Editing in Kendo UI and Web API

I am new to Web API and Kendo UI. My requirement is InCell Editing. I have implemented this with below reference links. But my problem is In controller action method i am getting count of employee as 0. I am not any other things means edited rows.
http://demos.telerik.com/kendo-ui/grid/editing
http://demos.telerik.com/aspnet-mvc/grid/editing
and another way I tried with below reference. But here also in JQuery I am getting what I updated rows. but when passing data to controller through AJAX call in controller I am getting count as 0. Please can you help this.
http://stackoverflow.com/questions/17033025/kendo-grid-batch-editing-making-a-single-call-to-save
Here is my code:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/Employee/GetEmployee",
dataType: "json"
},
create: {
url: "/api/Employee/CreateEmployee",
dataType: "json",
type: "POST",
complete: function (jqXhr, textStatus) {
// Do something
}
},
update: {
url: "/api/Employee/Update",
dataType: "json",
type: "POST",
complete: function (jqXhr, textStatus) {
// Do something
}
},
destroy: {
url: "/api/Employee/DeleteEmployee",
dataType: "json",
type: "DELETE",
complete: function (jqXhr, textStatus) {
// Do something
}
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 12,
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, type: "number" },
EmployeeId: {
editable: true, type: "text", validation: {required: true },
},
EmployeeName: { validation: { required: true } }
}
}
}
});
if (container.find('#gridEmployee').data().kendoGrid)
container.find('#gridEmployee').data().kendoGrid.destroy();
container.find("#gridEmployee").kendoGrid({
dataSource: dataSource,
pageable: true,
// toolbar: [{ text: "Add new Employee", className: "btn btn-primary grid-add-new-record" }, { text: "Save", className: "btnKendoUiSave" }],
toolbar: ["create", "save", "cancel"],
columns: [
{
command: [
//define the commands here
{ name: "edit", text: " " }, { name: "destroy", text: " " }, { name: "update", text: " ", click: showDetails }], width: "200px"
},
{ field: "EmployeeId", title: "Employee Id", format: "{0:0}", headerAttributes: { "data-localize": "FIELD_NUMBER" } },
{ field: "EmployeeName", title: "Employee Name", headerAttributes: { "data-localize": "FIELD_NAME" } },
],
editable: true,
});
Web API Controller:
[HttpPost]
public System.Web.Mvc.JsonResult Update([System.Web.Mvc.Bind(Prefix = "models")]List<PlantEmployeeModel> Employees)
{
//
}

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