jgGrid not displaying json data - json

This is driving me crazy, so any help would be awesome:
My html is as follow:
<asp:Content ID="Content3" ContentPlaceHolderID="Content" runat="server" class="MainLoginScreen">
<table id="StudyTable"></table>
<div id="StudiesPager"></div>
</asp:Content>
My javascript is as follows:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#StudyTable").jqGrid({
url: '/StudyManager/GetStudyTable.aspx',
datatype: "json",
mtype:"GET",
colNames: ['Name', 'URL', 'Creation Date', 'Description', 'Status'],
colModel:[
{ name: 'Name', width: 200},
{ name: 'URL', width: 100 },
{ name: 'Creation_Date', width: 300},
{ name: 'Description', width: 200 },
{ name: 'Status', width: 200}
],
rowNum:10,
rowList:[10,20,30],
viewrecords: true,
sortname: 'Name',
sortorder: "asc",
pager: $('#StudiesPager'),
imgpath: '/Content/Images',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: true,
cell: "cell",
id: "id"
},
width: 800,
height: 400
});
});
</script>
and my cs code is:
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.Append("{'total':1,");
sb.Append("'page':'1',");
sb.Append("'records':'1',");
sb.Append("'rows': [");
sb.Append("{ 'id':'123', 'cell':['abc','abc','abc','abc','abc']}");
sb.Append("]}");
Response.Clear();
Response.StatusCode = 200;
Response.Write(sb.ToString());
Response.End();
}
The table and pager are displayed perfectly, but no data is rendered to the table.
The returned json from my cs seems to be in the correct format:
{'total':1,'page':'1','records':'1','rows': [{ 'id':'123', 'cell'['abc','abc','abc','abc','abc']}]}
But no data is being displayed in the grid.

Also you can create something like:
public class JqGridJsonData
{
public int Total {get;set;}
public int Page {get;set;}
etc
}
And serialize this to json with Json.NET
http://james.newtonking.com/pages/json-net.aspx

Of all things that could cause the problem - it was the single quotations. JSON doesnt seem to allow 'word', but rather needs \"word\".
So the output json from the cs should have been :
{"total":"1","page":"1","records":"1","rows": [{ "id":"123", "cell"["abc","abc","abc","abc","abc"]}]}

Related

Bootstrap-Table data-url receiving records but not showing data in MVC

When calling a method, GetEmployee in this example, it is correctly showing 2 records but with a dash instead of the data. I'm guessing it is a Json issue in the controller but have been unable to find a solution. Here is a simplified case that I've been prototyping. Thanks in advance!
CONTROLLER
public JsonResult GetEmployees()
{
List<EmployeeViewModel> employees = new List<EmployeeViewModel>()
{
new EmployeeViewModel { EmployeeName = "Steve", PostalCode = "90210" },
new EmployeeViewModel { EmployeeName = "Jane", PostalCode = "41111" }
};
return Json(employees);
}
VIEW
<script type="text/javascript">
$(function () {
$("#myTable").bootstrapTable({
url: '/Home/GetEmployees',
method: 'get',
pageSize: 10,
pageNumber: 1,
pagination: true,
columns: [
{
field: 'EmployeeName',
title: 'Employee Name',
sortable: true
},
{
field: 'PostalCode',
title: 'Postal Code',
sortable: true
}
]
});
});
</script>
<div class="container">
<div class="row">
<table id="myTable"></table>
</div>
</div>
web page
javascript is case sensitive and uses camel case property names. try this
.....
{
field: 'employeeName',
title: 'Employee Name',
sortable: true
},
{
field: 'postalCode',
title: 'Postal Code',
....

How to bind JSON data to jqgrid?

I am trying to bind json formatted data to Jqgrid.This is simple website application.I have tried for customized table.Now I want to bind it by using jqgrid.
.aspx or script Code is as follows:
<script src="JS/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "JQGridBindData.aspx/GetAllDetails",
data:{},
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (result) {
var data = JSON.parse(result.d);
var array = data.Table;
colNames: ['Country_Code', 'Country', 'ISD_Code']
colModel: [
{name: 'Country_Code', index: 'Country_Code', width: 60, sorttype: "int"},
{name: 'Country', index: 'Country', width: 60, sorttype: "string"},
{name: 'ISD_Code', index: 'ISD_Code', width: 60, sorttype: "string"}
]
},
multiselect: true,
rowNum: 10,
rowList: [5, 10, 20, 50, 100],
pager: jQuery('#pager1'),
sortorder: "desc",
viewrecords: true,
caption: "Manipulating Array Data",
error: function (){
alert(JSON.stringify(Error));
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="jQGridDemo">
</table>
<div id="jQGridDemoPager">
</div>
<br />
<br />
</form>
in my .cs page i am getting the values like this. my .cs side code is
[WebMethod]
public static string GetAllDetails()
{
Generic gn = new Generic();
DataSet ds = gn.ExecuteDataset("Country_master_view", 0);
string data = JsonConvert.SerializeObject(ds,Formatting.Indented);
return data;
}

Frontend - Add new use jqGrid?

I use jqGrid add new record, but i can't put data from grid to json string.
When i run, return code:
error Status: 'Unsupported Media Type'. Error code: 415
And my code:
$(document).ready(function () {
jQuery("#jQGridDemo").jqGrid({
url: 'http://192.168.1.59:8080/sunrise/api/v1/warehouse/getById/1',
mtype: "GET",
contentType: "application/json",
datatype: "json",
colNames: ['wareHouseID', 'name' , 'fullname' , 'company', 'address'],
colModel: [
{ name: 'wareHouseID', index: 'wareHouseID', width: 150,editable:false, editoptions:{readonly:true, size:10}, hidden:true},
{ name: 'name', index: 'name', width: 150,editable:true, editoptions:{size:30}},
{ name: 'fullname', index: 'fullname', width: 150,editable:true,editoptions:{size:30}},
{ name: 'company', index: 'company', width: 150,editable:true,editoptions:{size:30}},
{ name: 'address', index: 'address', width: 150,editable:true,editoptions:{size:30}}
],
rowNum: 10,
rowList:[10,20,30],
width: 1290,
sortname: 'wareHouseID',
sortorder:"desc",
height:235,
gridview: true,
viewrecords: true,
caption: "List User Details",
editurl:"http://192.168.1.59:8080/sunrise/api/v1/warehouse/update",
pager: "#jQGridDemoPager",
ajaxRowOptions : {
type :"POST",
contentType :"application/json",
dataType :"json"
},
serializeRowData: function(postData){
return JSON.stringify(postData);
}
});
$("#jQGridDemo").jqGrid('navGrid','#jQGridDemoPager',
{edit:true, add:true, del:false, search:true},
// Edit options
{
type:"PUT",
url:"http://192.168.1.59:8080/sunrise/api/v1/warehouse/update",
closeAfterEdit:true,
reloadAfterSubmit:true,
onclickSubmit: function(params, postData) {
return JSON.stringify(postData);
},
afterSubmit: function(response, postData) {
var res = jQuery.parseJSON(response.responseText);
return [true, "", res.d];
}
},
//Add option
{
type:"POST",
url:"http://192.168.1.59:8080/sunrise/api/v1/warehouse/new",
closeAfterAdd:true,reloadAfterSubmit:true,
onclickSubmit: function(params, postData) {
return JSON.stringify(postData);
},
afterSubmit: function(response, postData) {
var res = jQuery.parseJSON(response.responseText);
return [true, "", res.d];
}
}
);});
Could you help me to find a problem and how to fix it? Tks very much.
There are many unclear parts in your code. Nevertheless I guess that the main problem which you have is the following: you use ajaxRowOptions to set contentType and you use serializeRowData to serialize the data from request as JSON. The problem is: you use form editing, but ajaxRowOptions and serializeRowData will be used only in case of inline editing.
So you should use
ajaxEditOptions: { contentType :"application/json" },
serializeEditData: function (postData) {
return JSON.stringify(postData);
}
You have to remove onclickSubmit which returns JSON.stringify(postData) additionally.
I hope it should solve the problem. If it will not help then you should write first of all which version of jqGrid you use and which fork of jqGrid you use (free jqGrid, Guriddo jqGrid JS or some old jqGrid in version <= 4.7). You should write additionally more information about the server which reruns the error "'Unsupported Media Type'. Error code: 415".

Web API Odata not returning correct metadata

I'm using OData v4 with Web API to communicate with my AngularJS web application.
More specifically I'm trying to display my data using Kendo UI Grid.
My problem is, that my Web API does not return the correct metadata, resulting in Kendos datasource not being able to display the data.
I'm doing paging, and to do that I need the "count" property in my response for Kendo UI Grid datasource to be able work properly.
The response I'm expecting the Web API should look something like this:
http://docs.oasis-open.org/odata/odata-json-format/v4.0/errata02/os/odata-json-format-v4.0-errata02-os-complete.html#_Toc403940644
However, the result I'm seeing in the response is:
{
"#odata.context":"http://localhost:1983/odata/$metadata#TestReports","value":[
{
"Id":1,"Name":"Test Testesen","Purpose":"Kendo UI Grid Test","Type":"Rumraket","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":2,"Name":"Gunner Testesen","Purpose":"OData Web API Test","Type":"Sutsko","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":3,"Name":"Bertram Didriksen","Purpose":"Server Paging Test","Type":"Flyver","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":4,"Name":"Oluf Petersen","Purpose":"Test","Type":"B\u00e5d","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":5,"Name":"Alfred Butler","Purpose":"Opvartning","Type":"Batmobil","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
}
]
}
My code for retrieving the data is:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "odata"
},
parameterMap: function (options, type) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
console.log(paramMap);
delete paramMap.$inlinecount; // <-- remove inlinecount parameter
delete paramMap.$format; // <-- remove format parameter
console.log(paramMap);
return paramMap;
}
},
schema: {
data: function (data) {
return data; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data.length; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};
My WebApiConfig class is corrently like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.InsertRange(0, ODataMediaTypeFormatters.Create());
config.MapODataServiceRoute(
routeName: "odata",
routePrefix: "odata",
model: GetModel()
);
}
public static Microsoft.OData.Edm.IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<TestReport>("TestReports");
return builder.GetEdmModel();
}
}
Does anyone have any suggestions on how I get the Web API to return the correct metadata?
Apparently Kendo UI Grid is not supporting OData v4.
The fix was to modify the parameterMap of the Kendo datasource, and tell it to use $count instead of $inlinecount.
Besides that I had to tell the schema to read "#odata.count" as the "total" value.
After I edited the before posted code to the ode below, I got the correct data in my response:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "json"
},
parameterMap: function (options, type) {
var d = kendo.data.transports.odata.parameterMap(options);
delete d.$inlinecount; // <-- remove inlinecount parameter
d.$count = true;
return d;
}
},
schema: {
data: function (data) {
return data.value; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data['#odata.count']; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};

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