JQgrid not showing data while rows are generating - json

Jqgrid is not showing JSON data, however rows are generating
Server side code:
public JsonResult Denominations()
{
.
.
int counter = 0;
var jsonData = new
{
total = result.UserObject.Count,
page = 1,
rows = (
from p in result.UserObject
select new
{
id = ++counter,
cell = new string [] {
p.CurrencyID.ToString(),
p.DenominationID.ToString(),
p.DenominationName.ToString(),
p.DenominatorCount.ToString(),
p.Multiplier.ToString(),
p.TenderID.ToString()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Data from server side is like this:
{"total":1,"page":1,"rows":[{"id":1,"cell":["1","1","Penny","0","0.0100","1"]}]}
JavaScript code:
$("#denominators").jqGrid({
url: '/Denominations?tenderid=1&currencyid=1',
contentType: "application/json",
datatype: "json",
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
repeatitems: false,
cell: 'cell',
id: 'id',
userdata:'userdata'
},
mtype: "GET",
colNames: ["CurrencyID", "DenominationID", "TenderID", "Multiplier", "DenominationName", "DenominatorCount"],
colModel: [
{ name: "currencyid", width: 80, align: "center" },
{ name: "denominationid", width: 90, align: "center" },
{ name: "tenderid", width: 250 },
{ name: "multiplier", width: 250 },
{ name: "denominationname", width: 95 },
{ name: "denominatorcount", width: 95 },
],
height: 'auto',
loadonce: true,
sortname: "DenominationID",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true
});
View:
<table id="denominators" ></table>
View creates the grid with column header however rows are generated but rows did not any data int.

You use wrong jsonReader. To be exactly the property repeatitems: false is false. It means that the format of every item in rows array is
{
"currencyid": "1",
"denominationid": "1",
"tenderid": 1,
"denominationname": "Penny",
"denominatorcount": "0",
"multiplier": "0.0100"
}
You use
{
"id": 1,
"cell": [
"1",
"1",
"Penny",
"0",
"0.0100",
"1"
]
}
instead. So you should remove jsonReader because the format of input data corresponds the default jsonReader, but you need still reorder the columns of the grid or change the order of items which you place in cell array so that it corresponds the order of columns in colModel.
Additional remarks: you use wrong value for total. It should be the number of pages. By the way you use loadonce: true. In the case you can remove "total":1,"page":1 part from the response and just return array of named items. You should just choose the names of columns the same as the names of properties if the items.

Related

fill the filter values of a column by it's own values in kendo

I have a kendo grid which is filled with some JSON data,
in the filter window in the grid, you can select a condition Type and then fill the condition value text box and then filter the grid based on your selection.
now I have a column that is filled with just four or five different value.
I want to make the condition value field of the filter section to become a drop-down list and instead of writing those values to select them, I want to choose them from the list. ( I mean in the filter section of the grid column, not in the column itself.)
I read an article which was like what I wanted, but it had added those values in the code,
I should notify you that those fields are not the same each time, so I can't write those value in the filter by hard coding.
even something like this one is very similar to what I wanted ( Filter Condition Created For 'City' Field ), but it's using a different source for getting the condition drop-down values, not grid column itself.
in addition, I can't use JSON data, I must use the information from the kendo grid.
thanks in advance.
I found the solution to my problem at last...
after binding the grid to the data source, by setting a loop on the data source of the grid, I take data of one column of the grid and push it to an array, then I set the filter on that column to the array.
<script type="text/javascript">
var arrayName = [];
$(function () {
var productsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "api/products",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'GET'
},
parameterMap: function (options) {
return kendo.stringify(options);
}
},
schema: {
data: "Data",
total: "Total",
model: {
fields: {
"Id": { type: "number" },
"Name": { type: "string" },
"IsAvailable": { type: "boolean" },
"Price": { type: "number" }
}
}
},
error: function (e) {
alert(e.errorThrown);
},
sort: { field: "Id", dir: "desc" },
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
productsDataSource.read();
$("#report-grid").kendoGrid({
dataSource: productsDataSource,
dataBound:
function (e) {
var data = $("#report-grid").data("kendoGrid").dataSource._data;
for (i = 0; i < data.length; i++) {
arrayName.push(data[i].Name);
}
},
autoBind: false,
scrollable: false,
pageable: true,
sortable: true,
filterable: { extra: false },
reorderable: true,
columnMenu: true,
columns: [
{ field: "Id", title: "No", width: "130px" },
{ field: "Name", title: "ProductName", filterable: { ui: SystemFilter } },
{
field: "IsAvailable", title: "Available",
template: '<input type="checkbox" #= IsAvailable ? checked="checked" : "" # disabled="disabled" ></input>'
},
{ field: "Price", title: "Price", format: "{0:c}" }
]
});
function SystemFilter(element) {
element.kendoDropDownList({
dataSource: arrayName,
optionLabel: "--Select Name--"
})
};
});
One way that I like to do this is to create a list of my values and add that list to ViewData, which then gets passed to the View.
public IEnumerable<ModelName> GetTypes()
{
//Get data from the table you store your values in.
return dbContext.TypesTable.OrderBy(f => f.Name);
}
public ActionResult YourView()
{
IEnumerable<ModelName> types = GetTypes();
ViewData["MyTypes"] = types;
return View();
}
Then in your grid add a ForeignKey column and set it to look at the ViewData you set earlier.
#(Html.Kendo().Grid<ViewModelName>()
.Name("GridName")
.Columns(columns =>
{
columns.ForeignKey(c => c.RecipientType, (System.Collections.IEnumerable)ViewData["MyTypes"], "TypeId", "Name");
})
)
This column will now display the Name of your value for the current records. Then when you go to edit or add a record, this field will display as a dropdown with all of the possible values.

SAPUI5 aggregation of tables doesn't work

I'm new to SAPUI5 and I'm trying to aggregate some JSON data before displaying in a column chart.
Here are some lines of my code:
var xsodataURL = 'That is my URL to my xsodata';
var oModelBU = new sap.ui.model.odata.ODataModel(xsodataURL, false);
oModelBU.bindList('/PM_PROJECT', false, {
select: 'PMBudget, PMActual, PMEAC'
});
var oDatasetBU = new sap.viz.ui5.data.FlattenedDataset({
dimensions: [{
axis: 1,
name: 'ProgramID: Overall Result',
value: ''
}],
measures: [
[{
name: 'Budget',
value: '{PMBudget}'
}, {
name: 'Actual',
value: '{PMActual}'
}, {
name: 'EAC',
value: '{PMEAC}'
}]
],
data: {
path: '/PM_PROJECT'
}
});
var oChartBU = new sap.viz.ui5.Column({
width: '100%',
height: calcChartHeight,
legendGroup: {
layout: {
position: 'bottom'
}
},
plotArea: {
colorPalette : d3.scale.category20().range()
},
title: {
visible: true,
text: 'Budget use in mEUR',
alignment: 'left'
},
dataset: oDatasetBU
});
oChartBU.setModel(oModelBU);
Actually everything works fine, but the application just display the JSON data of the last item in my xsodata. That's why I tried to aggregate the data in the xsodata file like:
"PM_SHOWCASE"."PM_PROJECT" aggregates always(SUM of "PMBudget", SUM of "PMActual", SUM of "PMEAC");
But that doesnt work - does anyone know, how I can display ALL data aggregated as SUM of the table "PM_PROJECTS"? Thanks in advance!
Have a great day, Arne.

JQXGrid lists all json data under first column

// I am using a JQXGrid, and while populating the grid with valid JSON string (I checked) it forms the columns perfectly (headers, footers, pageing, etc) but all the data is listed under the first column. I have been trying different settings for the last while and possibly a second set of eyes can see the error.
// Configure data source for data grid,...
var LocationDataSource =
{
datatype: "json",
datafields: [
{ name: 'Date' },
{ name: 'ProductCode' },
{ name: 'StoreNum' },
{ name: 'ProductQty', type: 'int' }
],
localdata: LocationData
};
// Configure Data Adapter and apply JSON data to it,...
var LocationDataAdapter = new $.jqx.dataAdapter(LocationDataSource);
// Apply data source to grid,...
$("#jqxLocationGrid").jqxGrid(
{
width: 900,
source: LocationDataAdapter,
pageable: true,
rowsheight: 50,
autoheight: true,
sortable: true,
altrows: true,
enabletooltips: true,
selectionmode: 'multiplecellsadvanced',
columns: [
{ text: 'Date', datafield: 'Date', width: 250 },
{ text: 'Product Code', datafield: 'ProductCode', width: 250 },
{ text: 'Store Number', datafield: 'StoreNum', width: 250 },
{ text: 'Product Qty', datafield: 'ProductQty', width: 250 }
]
});
I had the same issue and i fixed it, I forgot to add jqx.base.css to the default.aspx.

Kendo UI Grid JSON DataSource not loading data

For some reason I seem to be unable to get any more than the following in the Kendo UI Grid:
HTML:
<div id="grid"></div>
<script>
var remoteDataSource = new kendo.data.DataSource(
{
transport:
{
read: {
type: "POST",
dataType: "json",
url: "/home/getopportunities/"
}
},
pageSize: 4
})
$("#grid").kendoGrid(
{
dataSource: remoteDataSource,
columns: [
{
title: "Title",
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell"
},
width: 600,
filterable: true
},
{
title: "Activity Type",
headerAttributes: {
},
attributes: {
"class": "table-cell",
style: "text-align:center"
},
width: 100,
filterable: true
},
{
title: "Specialty",
filterable: true,
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell",
style: "text-align:center"
}
},
{
title: "Total Credits",
format: "{0}",
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell",
style: "text-align:center"
}
}
],
height: 430,
scrollable: true,
sortable: true,
pageable: true,
filterable: {
extra: false,
operators: {
string: {
contains: "Contains",
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
},
number: {
eq: "Is equal to",
neq: "Is not equal to",
gte: "Greater Than",
lte: "Less Than"
}
}
}
});
</script>
This is the JSON that is returned to it:
[
{"ActivityID":367,"Title":"Non Webinar Test For Calendar","ActivityType":"Other","TotalCredits":2,"Specialty":"[AB] [AE]"},
{"ActivityID":370,"Title":"Stage - Test SI Changes Part II","ActivityType":"Other","TotalCredits":2,"Specialty":"[NE]"},
{"ActivityID":374,"Title":"Webinar Test Event For Calendar","ActivityType":"Webinar","TotalCredits":2,"Specialty":"[FE] [NE] "},
{"ActivityID":401,"Title":"Module #1 Webinar: Learn Stuff","ActivityType":"Webinar","TotalCredits":2,"Specialty":"[AB] ",},
{"ActivityID":403,"Title":"Module #3 Webinar: Learn Even More Stuff","ActivityType":"Webinar","TotalCredits":2,"Specialty":"[AB] [AE]",}
]
I feel like I'm really close but am missing the last piece. Any help would be GREATLY appreciated as I'm on a deadline.
common troubles are with missing schema attribute !
add it to grid's - datasource, and check if it is set when you make your json.
(when plain array is serialized/to_json, the data array needs a property indicating the shema)
here an example to make it clear:
js: sample grid initialisation / datasource:
$("#grid").kendoGrid({ dataSource: { transport: { read: "/getdata/fromthisurl" }, schema: { data: "data" } } });
when you make / output your json, see if shema information is in the encoded result:
php:
$somedata= get_my_data();
header("Content-type: application/json");
echo "{\"data\":" .json_encode($somedata). "}";
or:
$viewdata['data'] = get_my_data();
header("Content-type: application/json");
echo (json_encode($viewdata));
so the json that is sent to the grid would look like:
{data:
[
{item}
{item}
]
}
instead of just:
[
{item}
{item}
]
Code looks good. I wonder if you change data source creation as below . Change type from POST to GET and see if it works,
var remoteDataSource = new kendo.data.DataSource(
{
transport:
{
read: {
type: "GET",
dataType: "json",
url: "/home/getopportunities/"
}
},
pageSize: 4
})
Try this,
$(document).ready(function () {
var remoteDataSource = new kendo.data.DataSource(
{
transport:
{
read: {
type: "POST",
dataType: "json",
url: "/home/getopportunities/"
}
},
pageSize: 4
});
});
You can see what part of code raise an exception in some debug tool (I'd recommend you Chrome's DevTools (just press F12 key in Chrome).
I'm pretty sure the problem is misssing field attribute in your grid's columns array, so Kendo don't know what data from datasource to display in what column of grid.
columns: [
{
field: "Title", // attr name in json data
title: "Title", // Your custom title for column (it may be anything you want)
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell"
},
width: 600,
filterable: true
},
Don't forget to change request type from "POST" to "GET".
What I found when inspecting the JSON coming back from the grid datasource json query was the field names were being JavaScripted -- what was ActivityID in C# became activityID on the wire...
This is unclean, and I discovered it by accident, but what worked for me was returning Json(Json(dataList)) from the controller instead of Json(dataList).

JQGrid and JSON data from Web2py

Q1.json is working (index.json). but i cant display in the jqgrid. i think colmodel names is the problem.Is it required that the colModel name is from database field? i want to display in jqgrid is from my select statements and those variables is from different tables. Not only one table but 3 tables.
Q2.Same row should be displayed in jqgrid but from different table. is it possible?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url:'{{=URL(r=request,f='call',args=['json','index'])}}',
data: "{}",
datatype: 'json',
mtype: 'GET',
contentType: "application/json; charset=utf-8",
complete: function(jsondata, stat) {
if (stat == "success") {
var thegrid = jQuery("#list")[0];
thegrid.addJSONData(JSON.parse(jsondata.responseText).d);
}
},
colNames:['code','name','max','min','quantity','amount'],
colModel :[
{name:CODE',index:'CODE', width:55},
{name:'Name', index:'Name',width:100},
{name:'MAX(table2.hour)', index:'MAX(hour)',width:100},
{name:'MIN(tabl2.hour)', index:'MIN(hour)',width:100},
{name:'SUM(quantity)', index:'SUM(quantity)',width:180},
{name:'SUM(amount)', index:'SUM(amount)',width:180}
],
hidegrid: false,
scrollOffset:0,
pager: '#pager',
rowNum:100,
shrinkToFit:false,
//rowList:[10,20,30,50],
//sortname: 'id',
//sortorder: 'desc',
viewrecords: false,
width: "100%",
height: "100%",
caption: 'SALES Grid'
});
});
</script>
{"rows": [0, {"table1": {"Name": "dyon"}, "_extra": {"MAX(table2.hour)": "20130514214301484", "MIN(table2.hour)": "20130514052610093", "SUM(table2.quantity)": 2115.854, "SUM(table2.amount)": 90089.15}, "table3": {"CODE": 1800}}]}
NOTE: i want to display the data in one page only.when i run the index.html it contains rows but it is blank and theres a rows contains 0 per cell.When i run the index.json it contains the data i needed. Im newbie to python. thanks!
The first problem is that you use many options of jqGrid which not exist (see the documentation): data, contentType, complete. You remove the options or use some other options which do what you probably tried to do.
The second problem is the usage of properties in JSON input which has dots inside (like SUM(table2.quantity) for example). To be able to read such properties you have to define jsonmap as function. For example
jsonmap: function (obj) {
return obj._extra["SUM(table2.quantity)"];
}
Because the JSON data have 0 as the first element you will have to fix the above code to somthing like
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["SUM(table2.quantity)"]: "";
}
The first demo demonstrate the results:
The best would be to fix your server code to remove the unneeded 0 item from rows array. If you can't do this on the server side you can do this on the client side inside of beforeProcessing callback.
The demo displays
It uses the following JavaScript code
$("#list").jqGrid({
url: "CrazyGirl.json", // need be changed to youth
datatype: "json",
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (data) {
return JSON.stringify({}); // send empty object (???)
},
colNames: ["code", "name", "max", "min", "quantity", "amount"],
colModel: [
{name: "code", width: 55, jsonmap: "table3.CODE"},
{name: "name", width: 100, jsonmap: "table1.Name"},
{name: "max", width: 120,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["MAX(table2.hour)"]: "";
}},
{name: "min", width: 120,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["MIN(table2.hour)"]: "";
}},
{name: "quantity", width: 100,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["SUM(table2.quantity)"]: "";
}},
{name: "amount", width: 100,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["SUM(table2.amount)"]: "";
}}
],
jsonReader: { repeatitems: false },
hidegrid: false,
pager: "#pager",
rowNum: 1000,
shrinkToFit: false,
height: "100%",
caption: "SALES Grid"
});