Grid Not populating in kendoGrid - asp.net-mvc

I am using MVC 4 and kendo UI for grid population. But the grid is not populating correctly.
this is my View :
<script type="text/javascript">
$.ajax({
url: '#Url.Action("Employee_Read", "UserSummary")',
type: 'GET',
dataType: "json",
Async: true,
success: function (data, textStatus, xhr) {
var dataloc = data;
var element = $("#grid4").kendoGrid({
dataSource: {
data: dataloc,
schema: {
model: {
fields: {
userDetailsId: { type: "number", editable: false },
name: { type: "string", editable: false },
roleId: { type: "string", editable: false },
emailId: { type: "string", editable: false }
}
}
}
}
});
}
});
</script>
Conroller ;
[HttpGet]
public ActionResult Employee_Read([DataSourceRequest]DataSourceRequest request)
{
using (var emp = new MockProjectAkarshEntities1())
{
IQueryable<tbl_UserDetails> userDetails = emp.tbl_UserDetails;
DataSourceResult result = userDetails.ToDataSourceResult(request);
return Json(result,JsonRequestBehavior.AllowGet);
}
In the output I am getting something like "[object][object]" and no of rows in the table returned from database.the skeleton of grid is coming but not the data. I am new to MVC and kendo. Please help me out.

The data you received should be started with {"Data": So simply change your code from var dataloc = data; to var dataloc = data.Data; just confirm it by visiting UserSummary/Employee_Read.
You can also set the dataSource later on like this (if you prefer at some stage)
<script type="text/javascript">
$.ajax({
url: '#Url.Action("Employee_Read", "UserSummary")',
type: 'GET',
dataType: "json",
Async: true,
success: function (data, textStatus, xhr) {
var dataloc = data.Data;
var element = $("#grid4").kendoGrid({
dataSource: {
// data: dataloc,
schema: {
model: {
fields: {
userDetailsId: { type: "number", editable: false },
name: { type: "string", editable: false },
roleId: { type: "string", editable: false },
emailId: { type: "string", editable: false }
}
}
}
}
});
// create data source using the data received
var ds = new kendo.data.DataSource({
data: dataloc
});
$('#grid4').data('kendoGrid').setDataSource(ds);
}
});
</script>

Related

How can I get the selected checkbox in kendo grid?

I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "Descripción" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.

Bind results from search

I cannot bind results from search in kendo grid. I've tried many times, I'm in trouble four days, I don't know what is wrong here,
When i debug action everything is working perfect,data is OK, return grid result are OK, but results aren't shown in kendo.
Here is my code:
<script>
$(function() {
$("a.k-button").on('click', function (e) {
debugger;
e.preventDefault();
var dataObj = serializeByFieldsWrap(".invoiceForm");
var dataUrl = $(this).data('url');
// dataObj.ToolboxId = toolboxId;
$('body').css('cursor', 'wait');
var result = $.ajax({
type: "POST",
url: dataUrl,
dataType: 'json',
data: dataObj,
//complete: $("#invoices-grid").data("kendoGrid").data.read(),
});
result.done(function (data) {
console.log(data);
var grid = $('#invoices-grid').data("kendoGrid");
grid.dataSource.data(data);
});
result.fail(function (error) {
console.log(error);
});
});
});
</script>
Controller:
public ActionResult List(DataSourceRequest command, FinanceListModel model)
{
var searchString = model.SearchJobItemNumber;
var isChecked = model.IsChecked;
var invoices = _invoiceService.GetAllInvoices(searchString, isChecked);
var gridModel = new DataSourceResult
{
Data = invoices.Select(x => {
var jobModel = x.ToModel();
return jobModel;
}),
Total = invoices.TotalCount
};
return Json(gridModel, "application/json", JsonRequestBehavior.AllowGet);
}
Kendo UI Grid:
<script>
$(function() {
$("#invoices-grid").kendoGrid({
dataSource: {
data: #Html.Raw(JsonConvert.SerializeObject(Model.Invoices)),
schema: {
model: {
fields: {
JobNumber: { type: "string" },
CustomerName: { type: "string" },
DepartmentName: { type: "string" },
DateInvoice: { type: "string" },
ValidDays: { type: "number" },
Delivery: { type: "string" },
IsPayed: { type: "boolean" },
Payed: { type: "number" },
Status: { type: "boolean" },
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: function () {
var row = this.element.find('tbody tr:first');
this.select(row);
},
columns: [
#*{
field: "Status",
title: "#T("gp.Jobs.Fields.Status")",
template: '#= Status #'
},*#
{
field: "JobNumber",
title: "#T("gp.Invoice.Fields.JobNumber")",
template: '#= JobNumber #'
},
{
field: "CustomerName",
title: "#T("gp.Invoice.Fields.CustomerName")",
template: '#= CustomerName #'
},
{
field: "DepartmentName",
title: "#T("gp.Invoice.Fields.DepartmentName")",
template: '#= DepartmentName #'
},
{
field: "DateInvoice",
title: "#T("gp.Invoice.Fields.DateInvoice")",
template: '#= DateInvoice #'
},
{
field: "ValidDays",
title: "#T("gp.Invoice.Fields.ValidDays")",
template: '#= ValidDays #'
},
{
field: "Delivery",
title: "#T("gp.Invoice.Fields.Delivery")",
template: '#= Delivery #'
},
{
field: "Payed",
title: "#T("gp.Invoice.Fields.IsPayed")",
template: '#= (Payed == 2) ? "Комп." : ((Payed == 1) ? "ДЕ" : "НЕ") #'
},
{
field: "Id",
title: "#T("Common.Edit")",
width: 100,
template: '#T("Common.Edit")'
}
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "popup"
},
scrollable: false,
selectable: true,
change: function(e) {
var selectedRows = this.select();
var jobId = parseInt($(selectedRows).data('job-id'));
var jobItemId = parseInt($(selectedRows).data('job-item-id'));
var result = $.get("#Url.Action("SideDetails", "Production")/" + jobItemId);
result.done(function(data) {
if (data) {
$(".job-edit .jobItemDetails").html(data);
}
});
},
rowTemplate: kendo.template($("#invoiceRowTemplate").html()),
});
});
</script>
DataSourceResult formats your server response like this:
{
Data: [ {JobNumber: "...", FieldName: "bar", ... } ],
Total: 100
}
In other words, the data items array is assigned to a Data field, and the total items count is assigned to a Total field. The Kendo UI DataSource configuration must take this into account by setting schema.data and schema.total:
http://docs.telerik.com/kendo-ui/framework/datasource/crud#schema
http://docs.telerik.com/kendo-ui/framework/datasource/crud#read-remote
schema: {
data: "Data",
total: "Total"
}

My Kendo grid is not populating with JSON object returned from Controller

I am writing an MVC application that is storing certain information in session variables. I am able to populate a list I have in my repo class without a problem. The issue I am having is when I click on my search Client controller it just gives me a JSON object but does not populate my Kendo Grid.
This is my datasource:
var clientSearch = new kendo.data.DataSource({
transport: {
read: {
url: "SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
create: {
url: "ClientInformation",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST"
},
parameterMap: function (data, operator) {
if (operator != "read")
return JSON.stringify(viewModel);
}
},
schema: {
model: {
id: "clientName",
}
}
});
This is my Grid:
$("#grid").kendoGrid({
dataSource: clientSearch,
columns: [{
field: "clientName",
title: "Client Name",
},
{
field: "clientNumber",
title: "Client Number",
},
{
field: "clientType",
title: "Client Type",
}]
})
This is my controller that is returning my JSON object:
[HttpGet]
public ActionResult SearchClient()
{
HttpSessionStateBase session = HttpContext.Session;
Repo repo = new Repo(session);
var result = repo.GetClient();
return Json(new
{
list = result,
count = result.Count
}, JsonRequestBehavior.AllowGet);
}
You need to specify your fields in the schema of data source object:
var clientSearch = new kendo.data.DataSource({
transport: {
read: {
url: "SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
create: {
url: "ClientInformation",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST"
},
parameterMap: function (data, operator) {
if (operator != "read")
return JSON.stringify(viewModel);
}
},
schema: {
model: {
id: "clientName",
fields: {
ID: { editable: false },
clientName: { editable: false },
clientNumber: { editable: false },
clientType: { editable: false }
}
}
});
Kendo.Mvc expects DataSourceRequest and DataSourceResult when binding grid as such:
public ActionResult SearchClient([DataSourceRequest] DataSourceRequest request)
{
HttpSessionStateBase session = HttpContext.Session;
Repo repo = new Repo(session);
var result = repo.GetClient();
return Json(new
{
list = result.ToList().ToDataSourceResult(request, ModelState)
}, "application/json", JsonRequestBehavior.AllowGet);
}

Data is getting but not populating in kendo grid using angular js

I am able to get the data from database but not populating in gridview.
here is my code below:
<div ng-app="app" ng-controller="MyCtrl">
<div kendo-grid k-options="gridOptions" k-rebind="gridOptions" k-pageable='{ "pageSize": 2, "refresh": true, "pageSizes": true }'></div>
</div>
<script>
angular.module("app", ["kendo.directives"]).controller("MyCtrl", function ($scope, $http) {
$scope.gridOptions = {
columns: [{ field: "EmployeeKey" }, { field: "FirstName" }],
dataSource: {
//schema: {
// data: "d"
//},
type: "jsonp",
transport: {
read: function (e) {
$http({ method: 'GET', url: '/Employee/Employee_Read' }).
success(function (data, status, headers, config) {
// alert('Sucess')
//debugger;
e.success(data)
}).
error(function (data, status, headers, config) {
alert('something went wrong')
console.log(status);
});
}
},
//pageSize: 5
}
}
});
</script>
and this is the controller page where i am getting data
public ActionResult Employee_Read ([DataSourceRequest] DataSourceRequest request )
{
//IQueryable<IEmployeeRepositary> employeeRep = employeeRepositary.Employees;
return Json(employeeRepositary.Employees.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
so after running my application i am checking through debugger this line
"e.success(data)" so in mouse hove i am getting the total records fetched from database. but not populating in gridview it is still showing blank.
please help me out from here.
Because you are returning collection which wrapped with DataSourceResult method.
return Json(employeeRepositary.Employees.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
instead of just its collection
return Json(employeeRepositary.Employees, JsonRequestBehavior.AllowGet);
You need to define your data source schema, please try this schema setup
schema: {
data: "Data",
errors: "Errors",
total: "Total",
model: {
id: "Id",
fields: {
Id: { editable: false, defaultValue: 0 },
//the rest field definition
}
}
}
and you can change your transport's read to something like this
read: {
type: "POST",
url: "/Employee/Employee_Read",
dataType: "json",
contentType: "application/json"
}
your final code should be like this
$scope.gridOptions = {
columns: [{ field: "EmployeeKey" }, { field: "FirstName" }],
dataSource: {
transport: {
read: {
type: "POST",
url: "/Employee/Employee_Read",
dataType: "json",
contentType: "application/json"
},
parameterMap: function(options, operation) {
return JSON.stringify(options);
}
},
pageSize: 5,
schema: {
data: "Data",
errors: "Errors",
total: "Total",
model: {
id: "EmployeeKey",
fields: {
EmployeeKey: { editable: false, defaultValue: 0 },
FirstName: {type: "string", validation: { required: true }}
}
}
}
}
}
and your controller like this
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Employee_Read ([DataSourceRequest] DataSourceRequest request )
{
var employees = employeeRepositary.Employees;
return Json(employees.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

Kendo UI Grid Update button not firing

I am developing a KendoUI Grid with Inline editable option in javascript and can't make Update button to fire click event and post the data to server side update event. Clicking on Update button won't even update the grid on client.
Hope someone can help me point out what I am doing wrong here.
This is not a duplicate to this as I have tired the jfiddle link in the answer and it is not working too.
kendo UI grid update function wont fire
<div id="grid"></div>
#section Scripts{
<script type="text/javascript">
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "Home/GetPupilsAsJson",
dataType: 'json'
},
update: {
url: "Home/UpdatePupils",
dataType: 'json',
type: 'POST'
}
},
pageSize: 5,
autoSync: true
});
$('#grid').kendoGrid({
dataSource: dataSource,
editable: "inline",
pageable: true,
columns: [{
field: "Id",
title: "Id",
width: 150,
hidden: true
}, {
field: "Firstname",
title: "Firstname",
width: 150
}, {
field: "Lastname",
title: "Lastname",
width: 150
}, {
field: "DateOfBirth",
title: "DateOfBirth",
width: 150
}, {
field: "Class",
title: "Class",
width: 150
}, {
field: "Year",
title: "Year",
width: 150
},
{
command: ["edit"],
width: 150
}]
});
});
</script>
}
HomeController
public ActionResult GetPupilsAsJson()
{
return Json(GetPupils(), JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
[HttpPost]
public void UpdatePupils(Pupil p)
{
//never reach here
}
I don't know why but fixed it by putting schema information.
schema: {
model: {
id: "Id",
fields: {
Firstname: { editable: true, validation: { required: true } },
Lastname: { validation: { required: true } },
DateOfBirth: { validation: { required: true } },
Class: { validation: { required: true } },
Year: { validation: { required: true } }
}
}
}
Use #Url.Action("GetPupilsAsJson", "Home")' so no need to pass base url in your update action like this BASEURL+ "Home/GetPupilsAsJson".
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("GetPupilsAsJson", "Home")',
dataType: 'json'
},
update: {
url:'#Url.Action("UpdatePupils", "Home")',
dataType: 'json',
type: 'POST'
}
},
pageSize: 5,
autoSync: true
});
use parameter map to pass model values
<script type="text/javascript">
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("GetPupilsAsJson", "Home")',,
dataType: 'json'
},
update: {
url: '#Url.Action("UpdatePupils", "Home")',
dataType: 'json',
type: 'POST'
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 5,
autoSync: true
});
Call Controller with parameterMap
public JsonResult UpdatePupils(string models)
{
return Json(..);
}
Is any of your cell text has HTML tags like < or >, remove them and click on update. The update event will fire.

Resources