jsGrid calling Controller .Net Core - Cells not loading data - ajax

Using jsGrid / .net core 2.2 / MVC I'm successfully returning data in my ajax call and logging to the console, but I can't figure out why the fields aren't populated?
My View
<div id="jsGrid"></div>
#section scripts {
<script>
$(function () {
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
//deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function () {
var d = $.Deferred();
$.ajax({
type: 'GET',
url: "/operator/GridJson",
dataType: "json",
success: function (data) {
d.resolve(data);
console.log('success ', data);
},
error: function (e) {
alert("error: " + e.responseText);
}
});
return d.promise();
}
},
fields: [
{ name: "OperatorId", type: "number", width: 50 },
{ name: "FirstName", type: "text", width: 150 },
{ name: "LastName", type: "text", width: 150 },
{ name: "LicenseNumber", type: "number", width: 50, filtering: false },
{ name: "RFIDNumber", type: "number", width: 50, filtering: false },
{ name: "DateCreated", type: "date", width: 50, filtering: false },
{ name: "LastUpdated", type: "date", width: 50, filtering: false },
{ name: "CompanyId", type: "number", width: 50 }
// { type: "control" }
]
});
console.log("test");
});
</script>
}
My Controller Method
[HttpGet]
public string GridJson()
{
List<OperatorDetail> operators = service.GetOperators();
string json = JsonConvert.SerializeObject(operators);
return json;
}
The Console log
(5) [{…}, {…}, {…}, {…}, {…}]
0: {OperatorId: 1, FirstName: "driver1", LastName: "driver1", LicenseNumber: 12345, RFIDNumber: 12345, …}
1: {OperatorId: 2, FirstName: "driver2", LastName: "driver2", LicenseNumber: 23456, RFIDNumber: 23456, …}
2: {OperatorId: 3, FirstName: "driver3", LastName: "driver3", LicenseNumber: 34567, RFIDNumber: 34567, …}
3: {OperatorId: 4, FirstName: "driver4", LastName: "driver4", LicenseNumber: 45678, RFIDNumber: 45678, …}
4: {OperatorId: 5, FirstName: "driver5", LastName: "driver5", LicenseNumber: 56789, RFIDNumber: 56789, …}
length: 5
__proto__: Array(0)

The reason is your loadData() async function returns before you get a response.
To fix that, change your loadData function to return a promise.
loadData: function(filter){
return $.ajax({
type:"GET",
url: "/operator/GridJson",
data:filter,
dataType:"JSON",
});
}
[Edit]
Actually, if you inspect the source with the F12 developer tool, you will find the fields rendered already. It turns out we also need change the height: "100%" as it will make those fields invisible.
Here's a complete list of a working sample:
$("#jsGrid").jsGrid({
width: "100%",
height: "100%",
height: "400px",
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
//deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function(filter){
return $.ajax({
type:"GET",
url: "/book/index",
data:filter,
dataType:"JSON",
});
}
},
fields: [
{ name: "OperatorId", type: "number", width: 50 },
{ name: "FirstName", type: "text", width: 150 },
{ name: "LastName", type: "text", width: 150 },
{ name: "LicenseNumber", type: "number", width: 50, filtering: false },
{ name: "RFIDNumber", type: "number", width: 50, filtering: false },
{ name: "DateCreated", type: "date", width: 50, filtering: false },
{ name: "LastUpdated", type: "date", width: 50, filtering: false },
{ name: "CompanyId", type: "number", width: 50 }
// { type: "control" }
]
});
A demo:

I recently had the same issue recently and took me a while to find someone else to point it out to me, too. itminus has a good portion of the solution, but since you have Paging enabled, you need to return your data in a specific JSON object.
{
data: [{your list here}],
itemsCount: {int}
}
It's barely in the documentation, as it's inline and not very obvious. (Bolding mine.)
loadData is a function returning an array of data or jQuery promise that will be resolved with an array of data (when pageLoading is true instead of object the structure { data: [items], itemsCount: [total items count] } should be returned). Accepts filter parameter including current filter options and paging parameters when
http://js-grid.com/docs/#controller

Related

on jquery ajax call , unable to bind jqgrid data

I have 2 queries on binding jgGrid in MVC application..
1. I am unable to bind jsonData which is coming from controller on Success callback method
2. On button click i am loading jqgrid from server data, but when i click 2nd time it is not firing my server code(which is in controller), only first time it is executing the server code.
below is my javascript code
function buildGrid() {
// setup custom parameter names to pass to server prmNames: { search: "isSearch", nd: null, rows: "numRows", page: "page", sort: "sortField", order: "sortOrder" }, // add by default to avoid webmethod parameter conflicts postData: { searchString: '', searchField: '', searchOper: '' }, // setup ajax call to webmethod datatype: function(postdata) { mtype: "GET", $.ajax({ url: 'PageName.aspx/getGridData', type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(postdata), dataType: "json", success: function(data, st) { if (st == "success") { var grid = jQuery("#list")[0]; grid.addJSONData(JSON.parse(data.d)); } }, error: function() { alert("Error with AJAX callback"); } }); }, // this is what jqGrid is looking for in json callback jsonReader: { root: "rows", page: "page", total: "totalpages", records: "totalrecords", cell: "cell", id: "id", //index of the column with the PK in it userdata: "userdata", repeatitems: true }, colNames: ['Id', 'First Name', 'Last Name'], colModel: [ { name: 'id', index: 'id', width: 55, search: false }, { name: 'fname', index: 'fname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} }, { name: 'lname', index: 'lname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} } ], rowNum: 10, rowList: [10, 20, 30], pager: jQuery("#pager"), sortname: "fname", sortorder: "asc", viewrecords: true, caption: "Grid Title Here" }).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false }, {}, // default settings for edit {}, // add {}, // delete { closeOnEscape: true, closeAfterSearch: true}, //search {} ) });
var grid = $("#jQGrid"); $("#jQGrid").jqGrid({
//setup custom parameter names to pass to server
prmNames: { search: "isSearch", nd: null, rows: "numRows", page: "page", sort: "sortField", order: "sortOrder" },
// add by default to avoid webmethod parameter conflicts
postData: {
'ddlDSVIN': function () {
return $('#ddlDevice :selected').val();
},
'search': function () { return $("#searchId").val(); },
'OEMType': function () { return $('#ddlOEM :selected').text(); },
'frmDate': function () { return fromDate.toDateString(); },
'toDate': function () { return toDate.toDateString(); }
},
datatype: function(postdata) { mtype: "POST",
$.ajax({ url: '/DataIn/DataInSearchResult/', type: "POST", contentType: "application/json; charset=utf-8",
//data: postData,
datatype: "json",
success: function(data, st) {
if (st == "success") {
var grid = jQuery("#jQGrid")[0]; grid.addJSONData(JSON.parse(data.d));
var container = grid.parents('.ui-jqgrid-view');
$('#showgrid').show();
$('#jQGrid').show();
$('#divpager').show();
//container.find('.ui-jqgrid-hdiv, .ui-jqgrid-bdiv').show();
$("#hideandshow").show();
$("#lblTotal").html($(this).getGridParam("records") + " Results");
$("#hideandshow2").hide();
}
},
error: function(error) { alert("Error with AJAX callback" + error); } }); }, // this is what jqGrid is looking for in json callback
jsonReader: { root: "rows", page: "page", total: "totalpages", records: "totalrecords", cell: "cell", id: "id", //index of the column with the PK in it
userdata: "userdata", repeatitems: true
},
// url: '/DataIn/DataInSearchResult/',
colNames: ["PayloadCorrelationId", "Asset", "Type", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
colModel: [
{ name: 'CorrelationId', index: 'CorrelationId', jsonmap: 'CorrelationId', hidden: true, width: 2, key: true },
// { name: "", index:'', editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "True:False" }, formatoptions: { disabled: false } },
{ name: 'Device', jsonmap: 'Device', width: '65px' },
{ name: 'Type', jsonmap: 'Type', width: '65px' },
{ name: 'DateReported', jsonmap: 'DateReported', width: '100px' },
{ name: 'ErrorType', jsonmap: 'ErrorType', width: '85px' },
{ name: 'Error', jsonmap: 'Error', width: '160px' },
{ name: 'Latitude', jsonmap: 'Latitude', width: '78px' }, { name: 'Longitude', jsonmap: 'Longitude', width: '78px' },
{ name: 'Payloadurl', jsonmap: 'Payloadurl', width: '180px', formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } }],
rowNum: 10, rowList: [10, 20, 30],
pager: jQuery("#divpager"), sortorder: "asc",
viewrecords: true, caption: "Grid Title Here"
}).jqGrid('navGrid', '#divpager', { edit: false, add: false, del: false }, {}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true}, //search
{ });
}
above method is called in document.ready function
$(documen).ready(function() {
("#buttonclick").click(function() {
buildGrid();
});
});
Can you please what was wrong with my code.. because i need to search on button click by passing the paramerter's to service method using postData {},but how to send this postData to url and bind the result to JqGrid.
thanks
Raj.
Usage of datatype as is not recommend way. Instead of that one can use datatype: "json". It informs that jqGrid should make for you the Ajax request using $.ajax method. One can use additional options of jqGrid to specify the options of the underlying $.ajax request.
The next problem you have in the code
$(documen).ready(function() {
$("#buttonclick").click(function() {
buildGrid();
});
});
The function buildGrid will be called every time if the user click on #buttonclick button. The problem is that you have initially the empty table
<table id="jQGrid"></table>
on your page, but after creating the grid (after the call $("#jQGrid").jqGrid({...});), the empty table will be converted in relatively complex structure of dives and tables (see the picture). The second call on non-empty table will be just ignored by jqGrid. It's the reason why the 2nd click on the button #buttonclick do nothing.
You can solve the problem in two ways. The first would be including $("#buttonclick").jqGrid("GridUnload"); before creating the grid. It would be destroy the grid and recreate the initial empty table. The second way os a little better. You can not destroy the grid at the second time, but to call $("#buttonclick").trigger("reloadGrid"); instead. It will force making new Ajax request to the server.
Minimal changing of your original code will follow us to about the following:
$(documen).ready(function() {
var $grid = $("#jQGrid");
$grid.jqGrid({
//setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: {
ddlDSVIN: function () {
return $('#ddlDevice').val();
},
search: function () {
return $("#searchId").val();
},
OEMType: function () {
return $('#ddlOEM')
.find("option")
.filter(":selected")
.text();
},
frmDate: function () {
return fromDate.toDateString();
},
toDate: function () {
return toDate.toDateString();
}
},
mtype: "POST",
url: '/DataIn/DataInSearchResult/',
datatype: "json",
ajaxGridOptions: { contentType: "application/json; charset=utf-8" },
loadComplete: function () {
$('#showgrid').show();
$('#jQGrid').show();
$('#divpager').show();
$("#hideandshow").show();
$("#lblTotal").html($(this).getGridParam("records") + " Results");
$("#hideandshow2").hide();
},
jsonReader: {
root: root: function (obj) {
return typeof obj.d === "string" ?
$.parseJSON(obj.d) :
obj.d;
},
total: "totalpages",
records: "totalrecords"
},
colNames: ["PayloadCorrelationId", "Asset", "Type", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
colModel: [
{ name: 'CorrelationId', hidden: true, width: 2, key: true },
// { name: "", index:'', editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "True:False" }, formatoptions: { disabled: false } },
{ name: 'Device', width: 65 },
{ name: 'Type', width: 65 },
{ name: 'DateReported', width: 100 },
{ name: 'ErrorType', width: 85 },
{ name: 'Error', width: 160 },
{ name: 'Latitude', width: 78 },
{ name: 'Longitude', width: 78 },
{ name: 'Payloadurl', width: 180, formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } }],
rowNum: 10,
rowList: [10, 20, 30],
pager: "#divpager",
sortorder: "asc",
viewrecords: true,
caption: "Grid Title Here"
}).jqGrid('navGrid', '#divpager', { edit: false, add: false, del: false },
{}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true} //search
);
$("#buttonclick").click(function() {
$grid.trigger("reloadGrid");
});
});

kendo grid server re filtering the data source

$(document).ready(function () {
var agenciesData = new kendo.DataToken.DataSource({
type: 'webapi',
transport: {
read: { url: "/api/Agencies/", dataType: "json", data: { activity: getActivity() } },
create: { url: "/api/Agencies", type: "POST", dataType: "json" },
destroy: { url: "/api/Agencies/{0}", type: "DELETE" },
update: { url: "/api/Agencies/{0}", type: "PUT" },
idField: "ID"
},
filter: [{ field: "Activity", operator: "eq", value: getActivity() }],
pageSize: 15,
page: 1,
total: 0,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
schema: {
data: "Data",
total: "Total",
model: {
id: "ID",
fields: {
ID: { editable: false, type: "number" },
AgencyName: { type: "string" },
AgentName: { type: "string" },
Address: { type: "string" },
City: { type: "string" },
Tel1: { type: "string" },
Tel2: { type: "string" },
Pele: { type: "string" },
Activity: { type: "number" },
ToDate: { type: "date" }
}
}
}
});
$("#agenciesGrid").kendoGrid({
dataSource: agenciesData,
toolbar: [{ text: "valid", className: "validAgents" }, { text: "not valid", className: "notValid" }, { text: "all", className: "allAgents" }, { text: "potential", className: "potetial" }],
editable: false,
navigatable: true,
sortable: true,
autoBind: false,
height: 430,
pageable: { refresh: true },
columns: [
{ field: "ID", hidden: true },
{ field: "AgencyName", title: "agency", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "AgentName", title: "agent", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "Address", title: "address", width: 200, template: "#= Address + ' ' + City #", filterable: false },
{ field: "Tel1", title: "phones", width: 300, template: "#= Tel1 + ' : ' + Tel2 + ' : ' + Pele #", filterable: false },
{ field: "Activity", title: "active", width: "90px" },
{ field: "ToDate", title: "end Contract", type: "date", width: 90, format: "{0:dd/MM/yyyy}", parseFormats: ["yyyy-MM-ddThh:mm:ss"] }
]
});
$(".validAgents").click(function () { //valid
$("#myActivity").val("1");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "1" });
});
$(".notValid").click(function () {//notValid
$("#myActivity").val("2");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "2" });
});
$(".potetial").click(function () {//potetial
$("#myActivity").val("3");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "3" });
});
});
function getActivity(){
var myActivity = $("#myActivity").val();
return myActivity;
}
When I use kendo grid already filtered by parameter like : $('#someGrid').data().kendoGrid.dataSource.read({ activity: value });
i see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=&activity=1
The grid is filter as expected but, when I want to do paging, sorting, refresh - I get the whole data ignoring the filter that i made.
and I see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=
How can I save my filter state to do paging and sorting on the data came from the server side ?
even when i used differen approach like "scrollable: { virtual: true }" and when i scroll down - every request is without the filtering...
Thanks
Did you try
var agenciesData = new kendo.DataToken.DataSource({
filter : function () {
return object;
}
});
I mean try using filter as a function and you can do your logic inside the function depending on the situation.

Kendo grid returning only one record

I´ve been searching all over the net to find an answer to this problem but with no success, my problem is with my Kendo ui grid which is returning just one record. The funny thing is, i have another grids that are returning all the records correctly, so i simply using the same code but there´s got be a detail that is escaping me so i was hopping someone could point on that, this is the code i´m using (CRUD):
var dataSource = new kendo.data.DataSource({
transport:
{
read:
{
url: "data/clientes.php",
},
update:
{
url: "data/clientes.php?type=update",
type:"POST",
complete: function(e)
{
$("#gridClientes").data("kendoGrid").dataSource.read();
}
},
destroy:
{
url: "data/clientes.php?type=destroy",
type: "POST"
},
create:
{
url: "data/clientes.php?type=create",
type: "POST",
complete: function (e) {
$("#gridClientes").data("kendoGrid").dataSource.read();
}
},
parameterMap: function(options, operation)
{
if (operation !== "read" && options.models)
{
return {models: kendo.stringify(options.models)};
}
}
},
error:function(e)
{
console.log(e);
//alert(e.message);
},
batch: true,
pageSize: 8,
schema:
{
data: "data",
total: function(response)
{
return $(response.data).length;
},
model:
{
id: "idCliente",
fields:
{
idCliente: { editable: false, nullable: true, type: "number"},
titulo: { validation: { required: false } },
primeiroNome: { validation: { required: true } },
ultimoNome: { validation: { required: true } },
morada: { validation: { required: false } },
codigoPostal: { type: "string",validation: { required: false} },
cidade: { validation: { required: false } },
pais: { validation: { required: false } },
estado: { validation: { required: false } },
telefone: { type: "string", validation: { required: false, min: 1} },
email: { validation: { required: false } },
passaporte: { validation: { required: false } },
bi: { type: "number", validation: { required: false} },
foto: { type: "string", validation: { required: false} },
comentarios: { validation: { required: false } },
NomeUtilizadorCriador: {editable: true,validation: { required: false } },
DataCriacao: {editable: false, validation: { required: false } },
NomeUtilizadorUpdate: {editable: true, validation: { required: false } },
DataUpdate: {editable: false, validation: { required: false } },
}
}
}
});
$("#gridClientes").kendoGrid({
dataSource: dataSource,
height: 550,
serverPaging: true,
pageable : true,
toolbar:[{name: "create",text: $varGridQuartosBtnNovoPT},{name: "close",text: "X"}],
editable : {mode : "popup",
window : {title: "Editar",}
},
columns: [
{ field: "titulo", title: "Título", width: "8px", },
{ field: "primeiroNome", title: "Primeiro Nome", width: "14px" },
{ field: "ultimoNome", title: "Ultimo Nome", width: "14px" },
{ field: "morada", title: "Morada", width: "11px" },
{ field: "cidade", title: "Cidade", width: "11px" },
{ field: "codigoPostal", title: "CEP", width: "9px", editor:numberEditor },
{ field: "pais", title: "País", width: "14px" ,editor: paisEditor},
{ field: "estado", title: "Estado", width: "10px", hidden: true },
{ field: "telefone", title: "Telefone", width: "12px",editor:numberEditor},
{ field: "email", title: "Email", width: "17px" },
{ field: "passaporte", title: "Passaporte", width: "15px", hidden: true },
{ field: "bi", title: "Bi", width: "10px", hidden: true ,editor:numberEditor},
{ field: "foto", title: "Foto", hidden: true, editor:fotoEditor},
{ field: "comentarios", title: "Comentários", hidden: true, editor: textareaEditor},
{ field: "NomeUtilizadorCriador", title: "Criado por", hidden: true,editor:numberEditor},
{ field: "DataCriacao", title: "Criado em", hidden: true, width: "10px"},
{ field: "NomeUtilizadorUpdate", title: "Atualizado por", hidden: true, editor:numberEditor},
{ field: "DataUpdate", title: "Atualizado em", hidden: true, width: "10px"},
{command:[{ text: "Detalhes", click: showDetails },{ name: "edit",text:"Editar"},{ name: "destroy",text:"Apagar"}],title:" ",width: "30px"}],
});
If my database is empty and i insert just one record, then it returns that record correctly, but if i hit the new button to insert another record, it inserts in the database but the kendo grid returns/displays nothing, Meanwhile i have discovered a difference between this kendogrid and the others(that are working correctly) when i open the chrome console, this one returns two objects "data":
0: {,…}
data: {0: "70", 1: "", 2: "jonh", 3: "sousa", 4: "", 5: "", 6: "", 7: "", 8: "", 9: "", 10: "", 11: "",…}
1: {,…}
data: {0: "73", 1: "", 2: "joana", 3: "banana", 4: "", 5: "", 6: "", 7: "", 8: "", 9: "", 10: "", 11: "",…}
the other kendogrids, only return one object data, why? i do not know because i´m using the same code. I thought it could be something related with my .php file, but then if it was, it shouldn´t even insert one record right?.
I also have this error when i call the grid:
Object {xhr: Object, status: "parsererror", errorThrown: SyntaxError: Unexpected end of input, sender: ht.extend.init, _defaultPrevented: false…}
this error appears when my database is empty. If i have one record, then the erro disappears and as i said before the grid displays correctly, BUT the error returns if i insert another record.
Sorry for the long post, thanks for your time, any help would be very appreciated.
Regards

Kendo ui odata request callback not supported

I am working on a odata grid with Kendo UI.
The problem is that the ajax request keeps containing a callback parameter. Which causes this error: Callback parameter is not supported. When I do the request manually without the callback, my odata service works perfect.
Someone an idea how to fix this?
$("#grid").kendoGrid({
dataSource: new kendo.data.DataSource({
type:"odata",
serverPaging: true,
serverFiltering: true,
serverSorting: true,
transport: {
contentType: "application/json; charset=utf-8",
type: "GET",
read: "/odata/FestivalSignUps?$inlinecount=allpages&$expand=PrefferedTasks/Task,AvailableDays,ApplicationUser",
dataType: "json",
parameterMap: function (options, type) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
delete paramMap.$format; // <-- remove format parameter.
return paramMap;
}
},
pageSize: 10,
schema: {
data: function (data) {
return data["value"];
},
total: function (data) {
return data["odata.count"];
},
}
}),
filterable:true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [
{ field: "ApplicationUser.Email", width: 90, title: "Email" },
{ field: "ApplicationUser.FirstName", width: 90, title: "Voornaam" },
{ field: "ApplicationUser.LastName", width: 90, title: "Achternaam" },
{ field: "PrefferedTasks", width: 90, title: "Taken",
template: "#= formatTasks(data) #"},
{ field: "Beschikbaar", width: 90, title: "Taken" }
]
});
Update
This code solved the problem:
$("#grid").kendoGrid({
dataSource: new kendo.data.DataSource({
type: 'odata',
transport: {
read: {
url: "/odata/FestivalSignUps?$expand=PrefferedTasks/Task,AvailableDays,ApplicationUser",
dataType: "json"
},
},
schema: {
data: function (data) {
return data["value"];
},
total: function (data) {
return data["odata.count"];
},
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
}),
filterable:true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [
{ field: "ApplicationUser.Email", width: 90, title: "Email" },
{ field: "ApplicationUser.FirstName", width: 90, title: "Voornaam" },
{ field: "ApplicationUser.LastName", width: 90, title: "Achternaam" },
{ field: "PrefferedTasks", width: 90, title: "Taken",
template: "#= formatTasks(data) #"},
{
field: "AvailableDays", width: 90, title: "Beschikbaar",
template: "#= formatDays(data) #"
},
]
});
I cover this issue and some others in a blog post that I wrote: Server-Side Filtering Using KendoUI With MVC4 WebAPI and OData.
If you are querying your own data, and don't need to do a cross-domain request, we can just not use jsonp. To do this, we just tell Kendo the dataType for the read operation is "json".
var dataSource = new kendo.data.DataSource({
type: 'odata', // <-- Include OData style params on query string.
transport: {
read: {
url: "/api/Albums",
dataType: "json"; // <-- The default was "jsonp".
}
}
});

Shifting of cell's value to right side

I'm working on kendoui. If we observe a grid then all the values are on the left side of each cell.I have a field of price and i want its value on the right side of cell.
Is it possible in kendo ui?
My code :-
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = ${grailsApplication.config.grails.serverURL}"+/course/,
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl+"listAll", dataType: "json",
cache: false
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models:
kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 15,
sort: { field: "dateCreated", dir: "desc" },
schema: {
model: {
id: "id",
fields: {
name: { editable: false, type: "string", validation: { required:
true, min: 1} },
type: { editable: false, type: "Type",validation: { required: true, min: 1}
},
fee: { editable: false, type: "double",validation: { required: true, min: 1}
},
duration: { editable: false, type: "integer", validation: { required: true, min: 1} },
status: { editable: false, type:"Status" , validation: { required: true, min: 1} }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
groupable:true,
sortable:true,
selectable:true,
height: 300,
columns: [
{field: "name",
title:'<g:message code="grid.billingServicesGroup.holidayName.label"
default="Course Name" />'},
{field: "type.name",
title:'<g:message code="grid.billingServicesGroup.reason.label"
default="Type of course" />'},
{field: "fee",title:'<g:message
code="grid.billingServicesGroup.code.label"
default="Fee" />'},
{field: "duration",title:'
<g:message code="grid.billingServicesGroup.holidayDate.label"
default="Duration(Year)" />'}
,
{field: "status.name",title:'<g:message
code="grid.billingServicesGroup.status.label" default="Status" />'},
],
editable: true,
change:function(e){
idOfData=this.select().data("id");
window.location.href=crudServiceBaseUrl+"show/"+idOfData;
},
saveChanges:function(){
},
remove:function(e){
/*alert(e.model.id.value);
selectedId=this.select().data("id");
$.ajax({
url:"http://localhost:8080/billing-
app/api/skeletonBill/"+selectedId,
type:"DELETE"
}).done(function(){alert('deleted')});*/
},
scrollable: {
virtual: true
}
});
});
</script>
You can use a column template to wrap the contents of all the cells in that column in for example a div-tag.
You can then use a class on the div to style the contents using CSS.
For example:
columns:
[{
field:"Department",
title:"Department",
width:80,
template: "<div class='foobar'>#= Department#</div>"
}]
/* CSS */
.foobar {
width: 100%;
text-align: right;
}

Resources