How to bind JSON data to jqgrid? - json

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

Related

Using jqGrid with .NET MVC Json Data won't load -columns showing ok

I am having a tough time loading data from .NET MVC 4.0.01 and I have been doing extensive research on the JQgrid site and documentation but cannot seem to find the issue.
And in my Grid (I'm using jqGrid 4.9.2)
$(function () {
gridMs = $("#jqGridMSats").jqGrid({
url: "Status/GetMissingItems",
//contentType: "application/json",
datatype: "json",
loadError: function (xhr, status, error) { alert(status + " " + error); },
mtype: "GET",
colNames: ["SattId", "SattUId", "SattScannedId", "SattName",
"SattAntenna", "SattCount", "SattFirstDiscovered", "SattLastSeen", "ZoneUId",
"ContainerId", "SattPlanUId", "Details"],
colModel: [{ name: "SattId", index: "SattId", hidden: false, width: 100 },
{ name: "SattUId", index: "SattUId", align: 'left', hidden: true, search: false, sortable: true, width: 75 },
{ name: "SattScannedId", index: "SattScannedId", align: 'left', search: false, sortable: true, width: 75 },
{ name: "SattName", index: "SattName", align: 'center', hidden: false, width: 30 },
{ name: "SattAntenna", index: "SattAntenna", align: 'center', hidden: false, width: 30 },
{ name: "SattCount", index: "SattCount", align: 'center', hidden: false, width: 30 },
{ name: "SattFirstDiscovered", index: "SattFirstDiscovered", align: 'center', hidden: true, formatter: 'date',
formatoptions: { newformat: "d-M-Y" }, search: true, sortable: true, width: 80,
searchoptions: {
dataInit: function (element) {
$(element).daterangepicker({
id: 'Discovered',
dateFormat: 'yy/mm/dd',
minDate: new Date(2014, 0, 1),
maxDate: new Date(2025, 0, 1),
showOn: 'focus',
onSelect: function () {
//var startDate = $(el).val().start;
//var endDate = $(el).val().end;
//alert("Start: " + startDate + " End: " + endDate);
}
});
},
// show search options
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{
name: "SattLastSeen", index: "SattLastSeen", align: 'center', stype: 'text', formatter: 'date',
formatoptions: { newformat: "d-M-Y" }, search: true, sortable: true, width: 90,
searchoptions: {
// dataInit is the client-side event that fires upon initializing the toolbar search field for a column
// use it to place a third party control to customize the toolbar
dataInit: function (el) {
$(el).daterangepicker({
id: 'drpLS',
dateFormat: 'yy/mm/dd',
minDate: new Date(2014, 0, 1),
maxDate: new Date(2025, 0, 1),
showOn: 'focus',
onClose: function () {
var misDate = $(el).val();
var dtArray = misDate.split('-');
var startdate = dtArray[0].trim();
var endDate = dtArray[1].trim();
}
});
},
// show search options
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "ZoneUId", index: "ZoneUId", align: 'center', sortable: true, width: 60 },
{ name: "ContainerId", index: "ContainerId", align: 'center', hidden: false, sortable: true, width: 60 },
{ name: "SattPlanUId", index: "SattPlanUId", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Details", index: "Details", align: 'center', width: 30, hidden: true, search: false, formatter: function (cellvalue) {
return "<img src='../../Content/finder.png' alt='Locate sat' />";
}
}
],
width: 770,
height: 'auto',
loadonce: true,
//rowNum: 11,
pager: "#jqGridPagerMSatts",
viewrecords: true,
caption: "Missing",
gridview: true,
autoencode: true,
footerrow: true,
loadComplete: function () { alert("loaded"); },
jsonReader: {
root: "rows",
repeatitems: false,
page: function (obj) { return 1; }, // page as 1
total: function (obj) { return 1; }, // total as 1
records: function (obj) { return obj.length; }
},
onCellSelect: function (rowid, index) {
var cm = gridMs.jqGrid('getGridParam', 'colModel');
if (cm[index].name == 'Details' && satValue.indexOf("----") == -1) {
alert('test');
}
},
});
gridMs.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, searchOperators: true });
gridMs.navGrid('#jqGridPagerMSatts', { edit: false, add: false, del: false, search: false });
});
My client side references:
<link href="<%= Url.Content("~/Scripts/jqGridM/css/ui.jqgrid.css") %>" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jqGridM/js/i18n/grid.locale-en.js") %>" ></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jqGridM/js/jquery.jqGrid.min.js") %>" ></script>
My columns load and the total records show. But cannot get the data to show. I've tried changing the controller to return a JavascriptSerializer format but still the same. I also removed the dates column thinking maybe it's a format issue but still the same results- no data shown. I get no errors at all when checking (Response) from Chrome. I have another grid in the same page which I can push dynamic data to just fine however loading the data from MVC Action is the problem. Is there something I am missing in my code? Any help would be greatly appreciated.
Here is how the FULL page renders in Chrome. If I invoke the missingTagGrid function first that Grid shows the data fine. Then if I select the resetGrid afterwards it loads fine too. If I select the resetGrid function first however the other grid won't load but it will show the colums and total pages....no errors in Chrome.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title></title>
<link href="/Content/Css/Reset.css" rel="stylesheet" type="text/css" />
<link href="/Content/Css/History.css" rel="stylesheet" type="text/css" />
<link href="/Content/Css/AnyTime.css" rel="stylesheet" type="text/css" />
<link href="/Content/Inventory/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="/Content/Inventory/ui.daterangepicker.css" rel="stylesheet" type="text/css" />
<link href="/Scripts/jqGridM/css/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<link href="/Content/Css/spectrum.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Scripts/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/Scripts/spectrum.js"></script>
<link type="text/css" href="/Content/telerik.common.min.css" rel="stylesheet"/>
<link type="text/css" href="/Content/telerik.vista.min.css" rel="stylesheet"/>
</head>
<body>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var inventoryData = [];
var missingData = [];
var mydata;
var rowMissing = 0;
var rowTotals;
var rowMissingMis = 0;
var rowtotalsMis;
var isMissing = false;
var mydata = [];
var newCompArray = [];
var machineName = 'bcd44e4c';
var registeredGrp = 'ACME Lgstks';
</script>
<form method="post" action="Status" id="form1"><div>
<div id="timeDiv"></div>
<div id="stsGrid" style="float: left;">
<div id="tagStatus" style="width: 560px;">
<div id="invGrid">
<table id="jqGrid"></table>
<div id="jqGridPager"></div></div>
<div id="misGrid">
<table id="jqGridMTags"></table>
<div id="jqGridPagerMTags"></div>
</div>
</div>
</div>
</div>
<div style="clear: both;">
</div>
</form>
<div id="removeChildModal" class="jqmWindow section">
</div>
<script type="text/javascript">
$('#misGrid').hide();
</script>
<script type="text/javascript">
function resetGrid() {
$('#misGrid').hide();
$('#invGrid').show();
var gridData;
var rowIds;
var messenger = $.connection.messenger;
$("#jqGridMTags").hide();
gridInv = null;
//<![CDATA[
$(function () {
'use strict';
var mydata = [], //Need this for SignalR
gridInv = $("#jqGrid");
gridInv.jqGrid({
datatype: "jsonstring",
datastr: inventoryData,
colNames: ["Antenna", "Content", "Count", "Direction", "Discovered", "Duration", "EPC", "Freq","LastSeen", "Name", "Pack", "RSSI", "Size", "Speed", "Title", "Type", "Zone", "Find"],
colModel: [{name: "Antenna", index: "Antenna", key: true, hidden: true, width: 100, cellattr: function (rowId) {if (rowId < 5) { return 'colspan=8'; }}
},
{ name: "Content", index: "Content", align: 'left', search: false, sortable: true, width: 75 },
{ name: "Count", index: "Count", align: 'center', search: false, sortable: true, width: 40 },
{ name: "Direction", index: "Direction", align: 'center', hidden: true, width: 30 },
{ name: "Discovered", index: "Discovered", align: 'center', stype: 'text', search: true, sortable: true, width: 80,
searchoptions: {
// dataInit is the client-side event that fires upon initializing the toolbar search field for a column
// use it to place a third party control to customize the toolbar
dataInit: function (element) {$(element).daterangepicker({id: 'Discovered',dateFormat: 'yy/mm/dd',minDate: new Date(2014, 0, 1),maxDate: new Date(2025, 0, 1),
showOn: 'focus'
});
},
// show search options
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "Duration", index: "Duration", align: 'center', hidden: true, width: 60 },
{ name: "EPC", index: "EPC", align: 'center', sortable: true, width: 140 },
{ name: "Freq", index: "Freq", align: 'center', hidden: true, sortable: true, width: 50 },
{
name: "LastSeen", index: "LastSeen", align: 'center', stype: 'text', search: true, sortable: true, width: 80,
searchoptions: {
dataInit: function (element) {$(element).daterangepicker({id: 'LastSeen',dateFormat: 'yy/mm/dd',minDate: new Date(2014, 0, 1),maxDate: new Date(2025, 0, 1),showOn: 'focus'});},
// show search options
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "Name", index: "Name", align: 'center', sortable: true, width: 50 },
{ name: "Pack", index: "Pack", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "RSSI", index: "RSSI", align: 'center', hidden: true, sortable: true, width: 50 },
{ name: "Size", index: "Size", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Speed", index: "Speed", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Title", index: "Title", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Type", index: "Type", align: 'center', width: 33, search: false, formatter: function (cellvalue) {
if (cellvalue == "----") return "----";
if (cellvalue == "None" || cellvalue === 'undefined' || cellvalue == '')
return "<img src='../../Scripts/Tree/skin/0000.png' alt='Locate tag' />";
else
return "<img src='../../Scripts/Tree/skin/" + cellvalue + ".png' alt='Locate tag' />";
}
},
{ name: "Zone", index: "Zone", align: 'center', search: true, sortable: true, width: 50 },
{ name: "Find", index: "Find", align: 'center', width: 25, search: false, formatter: function (cellvalue) {
if (cellvalue == "----") return "----";
else
return "<img src='../../Content/finder.png' alt='Locate tag' />";
}
}
],
width: 770,
height: 428,
gridview: true,
rowattr: function (rd) {
if (rd.Find === "----") { // verify it's Zone parent
return { "class": "zoneHdr" };
}
else
return { "class": "selected-row" };
},
loadonce: true,
rowNum: 11,
pager: "#jqGridPager",
sortname: 'Antenna',
treeGrid: true,
treeGridModel: 'adjacency',
treedatatype: "jsonstring",
ExpandColumn: 'Content',
viewrecords: true,
caption: "Inventory List",
footerrow: true,
grouping: false,
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
onCellSelect: function (rowid, index) {
var tagValue = gridInv.jqGrid('getCell', rowid, 'Title');
var zneValue = gridInv.jqGrid('getCell', rowid, 'Zone');
var cm = gridInv.jqGrid('getGridParam', 'colModel');
if (cm[index].name == 'Find' && tagValue.indexOf("----") == -1) {
localStorage.setItem("tagStore", tagValue);
localStorage.setItem("zneStore", zneValue);
}
window.location = "/Package";
},
});
gridInv.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, searchOperators: true });
gridInv.navGrid('#jqGridPager', { edit: false, add: false, del: false, search: false });
gridInv.navButtonAdd('#jqGridPager', {
caption: "Click to show missing tags",
buttonicon: "ui-icon-tag",
position: "last",
onClickButton: function () {
alert("Deleting Row");
}
});
});
gridData = $('#jqGrid').jqGrid('getRowData');
for (var key in gridData[0]) {rowIds = $('#jqGrid').jqGrid('getCol', key, true);
break;
}
if (typeof gridData != "undefined" && typeof rowIds != "undefined") {
$.each(gridData, function (id) {var $row = $('#' + rowIds[id].id);
$row.show();});
}
rowTotals = ($('#jqGrid').getGridParam('records') - 4);
rowMissing = 0;
$('#jqGrid').jqGrid("footerData", "set", { Content: "<span style='color:red'>Total Missing:</span>", Count: "<span style='color:red'>" + rowMissing + "</span>", LastSeen: "Total Inventoried:", Name: rowTotals });
$("#jqGrid").trigger("reloadGrid");
messenger.server.broadCastReaderConfig(false, '');
//
}
///Missing Tags
function missingTagGrid() {
$('#misGrid').show();
$('#invGrid').hide();
var gridMs = null;
//<![CDATA[
$(function () {
gridMs = $("#jqGridMTags").jqGrid({
url: "Status/GetMissingItems",
//contentType: "application/json",
datatype: "json",
loadError: function (xhr, status, error) { alert(status + " " + error); },
mtype: "GET",
colNames: ["TagId", "TagUId", "TagScannedId", "TagName", "TagAntenna", "TagCount", "TagFirstDiscovered", "TagLastSeen", "ZoneUId", "ContainerId", "FloorplanUId", "Details"],
colModel: [{ name: "TagId", index: "TagId", hidden: false, width: 100 },
{ name: "TagUId", index: "TagUId", align: 'left', hidden: true, search: false, sortable: true, width: 75 },
{ name: "TagScannedId", index: "TagScannedId", align: 'left', search: false, sortable: true, width: 75 },
{ name: "TagName", index: "TagName", align: 'center', hidden: false, width: 30 },
{ name: "TagAntenna", index: "TagAntenna", align: 'center', hidden: false, width: 30 },
{ name: "TagCount", index: "TagCount", align: 'center', hidden: false, width: 30 },
{
name: "TagFirstDiscovered", index: "TagFirstDiscovered", align: 'center', hidden: true, formatter: 'date',
formatoptions: { newformat: "d-M-Y" }, search: true, sortable: true, width: 80,
searchoptions: { dataInit: function (element) {
$(element).daterangepicker({
id: 'Discovered',
dateFormat: 'yy/mm/dd',
minDate: new Date(2014, 0, 1),
maxDate: new Date(2025, 0, 1),
showOn: 'focus',
onSelect: function () {
}
});
},
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "TagLastSeen", index: "TagLastSeen", align: 'center', stype: 'text', formatter: 'date',
formatoptions: { newformat: "d-M-Y" }, search: true, sortable: true, width: 90,
searchoptions: { dataInit: function (el) {
$(el).daterangepicker({
id: 'drpLS',
dateFormat: 'yy/mm/dd',
minDate: new Date(2014, 0, 1),
maxDate: new Date(2025, 0, 1),
showOn: 'focus',
onClose: function () {
var misDate = $(el).val();
var dtArray = misDate.split('-');
var startdate = dtArray[0].trim();
var endDate = dtArray[1].trim();
}
});
},
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "ZoneUId", index: "ZoneUId", align: 'center', sortable: true, width: 60 },
{ name: "ContainerId", index: "ContainerId", align: 'center', hidden: false, sortable: true, width: 60 },
{ name: "FloorplanUId", index: "FloorplanUId", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Details", index: "Details", align: 'center', width: 30, hidden: true, search: false, formatter: function (cellvalue) {
return "<img src='../../Content/finder.png' alt='Locate tag' />";
}
}
],
width: 770,
height: 'auto',
loadonce: true,
pager: "#jqGridPagerMTags",
viewrecords: true,
caption: "Missing",
gridview: true,
autoencode: true,
footerrow: true,
jsonReader: {
root: "rows",
repeatitems: false,
page: function (obj) { return 1; }, // page as 1
total: function (obj) { return 1; }, // total as 1
records: function (obj) { return obj.length; }
},
onCellSelect: function (rowid, index) {
var cm = gridMs.jqGrid('getGridParam', 'colModel');
if (cm[index].name == 'Details' && tagValue.indexOf("----") == -1) {
alert('Pop up to decribe missing tag in detail');
}
},
});
gridMs.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, searchOperators: true });
gridMs.navGrid('#jqGridPagerMTags', { edit: false, add: false, del: false, search: false });
});
}
<!-- other content -->
<script type="text/javascript" src="/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript" src="/Scripts/telerik.common.min.js"></script>
<script type="text/javascript" src="/Scripts/telerik.list.min.js"></script>
<script type="text/javascript" src="/Scripts/SignalR.StatusHub.js"></script>
<script type="text/javascript" src="/Scripts/trirand/jquery.jqDropDownList.min.js" ></script>
<script type="text/javascript" src="/Scripts/trirand/jquery.jqDatePicker.min.js" ></script>
<script type="text/javascript" src="/Scripts/trirand/jquery.jqAutoComplete.min.js" ></script>
<script type="text/javascript" src="/Scripts/jqGridM/js/i18n/grid.locale-en.js" ></script>
<script type="text/javascript" src="/Scripts/jqGridM/js/jquery.jqGrid.min.js" ></script>
<script type="text/javascript" src="/Scripts/jqGridM/js/jquery.jqGrid.src.js" ></script>
<script type="text/javascript" src="/Scripts/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.dialog.js"></script>
<script type="text/javascript" src="/Scripts/InventoryScripts/date.js"></script>
<script type="text/javascript" src="/Scripts/InventoryScripts/daterangepicker.jQuery.js"></script>
<script type="text/javascript" src="/Scripts/jquery.signalR-2.1.2.js"></script>
<script type="text/javascript" src="/signalr/hubs"></script>
</body>
</html>
You use wrong order of included JavaScript data and you placed some HTML element on the wrong place. For example you placed in <head> of the page the following JavaScript files
<script type="text/javascript" src="/Scripts/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/Scripts/spectrum.js"></script>
You have to include jQuery before jquery-1.11.0.min.js which depends from jQuery.
The next error: you included two different version of the same file. For example, You included jquery-1.11.0.min.js in the <head> and then placed jquery-ui-1.10.4.custom.js in the <body>. It's wrong. In the same way it's wrong to include both non-minimized and minimized version of the same JavaScript library. See jquery.jqGrid.src.js included directly after jquery.jqGrid.min.js.
You used jquery-1.7.1.js which is not an error, but I would strictly recommend you don't uses such retro version of jQuery. Instead of that you should use jQuery 1.11.3 or jQuery 2.1.4 if you don't need to support old web browsers IE6, IE7 and IE8.
I places <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> inside of <body>. It's wrong. All <meta> should be included directly after <title>. Don't forget to include
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
which is required to prevent using compatibility mode of IE.
Now about the code itself. It's difficult to read the code divided into many separate <script></script> parts. Moreover the code is either not full or some important functions will be not called or be called in the wrong order. You should first include jQuery, then include jqGrid and only after that you can use jqGrid method. Another problem: you define resetGrid and missingTagGrid function, but never call there (using resetGrid(); or missingTagGrid();).
One more problem: The code
$(function () {...});
is the short form of document ready function:
$(document).ready(function () {...});
which wait till the document which includes the <> is loaded and then execute the function inside of it (... part). In the case the usage of document ready inside of <body> (inside of the document) is not a good idea. You should wither remove $(function () { part, but place the code after HTML parts which you used in the handler (after <table id="jqGrid"></table> for example) or better to move the inside of <head>. Just examine once more the demo, which I posted before in the comment, under the aspect of the order included JavaScript files, the code, <head> and and <body>.
One more important aspect of JavaScript language: you should define variables of function inside of another outer function if it's possible. If you define variables directly on the top of the script like
<script type="text/javascript">
var inventoryData = [];
var missingData = [];
var mydata;
var rowMissing = 0;
var rowTotals;
var rowMissingMis = 0;
var rowtotalsMis;
var isMissing = false;
var mydata = [];
var newCompArray = [];
var machineName = 'bcd44e4c';
var registeredGrp = 'ACME Lgstks';
</script>
then you define global variables. It makes potential conflicts with another code which you included. For example if you would define $ = 0 or jQuery = null in the way you will break the code of jQuery and and jQuery plugins. It's important to understand additionally that the above script not only define global variables, it assign new properties to the global window object. You can easy verify that window object have rowMissing property now and the value of the property is 0. It would be much better to move the code inside of some function. For example the code
<script type="text/javascript">
$(function () {
var rowMissing = 0, rowTotals;
...
rowTotals = ($('#jqGrid').getGridParam('records') - 4);
$('#jqGrid').jqGrid("footerData", "set", {
Content: "<span style='color:red'>Total Missing:</span>",
Count: "<span style='color:red'>" + rowMissing + "</span>",
LastSeen: "Total Inventoried:",
Name: rowTotals
});
...
});
</script>
is much better. It defined local variables rowMissing and rowTotals existing only inside the function and it uses the variables inside of the function. In the way one will have no conflicts.
Ok, the biggest problem was Telerik's script register was embedding the older version of Jquery (jquery-1.7.1.js). I didn't notice it until you pointed it out. It's one of those things that Telerik does undercover so it was easy to miss. Great observation on the bad references, order and global vars, fixed those also. Thanks for all your help Oleg..you're truly awesome. Works like a charm now!

URL field not working with flexigrid no response from URL

When I pass the URL I am getting a no response from the url otherwise if I specify the corresponding WCF service page which is included in my project it is working is it any cross domain issue what would be the possible issue
<form id="sform" runat="server">
<table id="flex2" style="display:none"></table>
<script type="text/javascript">
$(document).ready(function () {
var user_id = 1;
var data = { UserID: user_id };
$("#flex2").flexigrid({
useInlineEditor: true,
//singleSelect: true,
rowClick: function (row) {
//var r=this.DataSource.rows[row.rowIndex];
//var p=$(row).offset();
//alert(r[this.DataSource.key]+" "+r.Name+" offset:"+p.top+","+p.left);
//this.grid.inlineEditor.edit(row);
},
url: 'http://192.168.10.91:5001/Service.svc/GetStates',
method: 'POST',
dataType: 'json',
colModel: [
{ display: 'Hours', name: 'hours', width: 40, sortable: true, align: 'center' },
{ display: 'DOC', name: 'doc', width: 180, sortable: true, align: 'left' },
],
searchitems: [
{ display: 'Type', name: 'cmetype' }
],
onError: function (jqXHR, textStatus, errorThrown) {
alert("flexigrid failed " + errorThrown + jqXHR + textStatus);
},
sortname: "type",
sortorder: "asc",
usepager: true,
title: 'States',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 800,
height: 200
});
});
//This function adds paramaters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit
function addFormData() {
//passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
var dt = $('#sform').serializeArray();
$("#flex2").flexOptions({ params: dt });
return true;
}
$('#sform').submit(function () {
$('#flex2').flexOptions({ newp: 1 }).flexReload();
return false;
});
</script>
</form>
Make sure that the svc service is accesibile and that it can accept post requests.
If all works well, check that the response is JSON and is valid.

how to display jqgrid from url (local data works, url data does not)

I have looked various question/answers on stackoverflow, but haven't found a solution.
When I use the first block of jqgrid code (data is local), the table and the data are displayed.
When I use the second block (data loaded from url), an empty table is displayed.
The strange part is that the local data is the actual content of the url file.
So I had assumed that the behavior would be identical.
Why can I not display the data using the url,
when the same data, if copied into the code, is displayed?
The HTML (calls mytest.js which contains the jqgrid code):
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.8.23.custom.css" />
<link rel="stylesheet" href="ui.jqgrid.css" />
<script src="jquery-1.8.0.min.js"></script>
<script src="jquery-ui-1.8.23.custom.min.js"></script>
<script src="grid.locale-en.js"></script>
<script src="jquery.jqGrid.min.js"></script>
<script src="mytest.js" type="text/javascript"></script>
</head>
<body>
<h1>hey</h1>
<table id="jqgrid"></table>
</body>
</html>
JSON as local data (data displays, [here, edited for brevity]):
var mydata = [
{"_id": {"$oid": "50a3f962b7718da1a3090fa9"},
"config": {"titlepage":
{"title": "My First Title",
"color": true,
"fontsize": "42/44",
}
}
},
{"_id": {"$oid": "50a3f962b7718da1a3090faa"},
"config": {"titlepage":
{"title": "My Second Title",
"color": true,
"fontsize": "42/44",
}
}
}
];
jQuery(document).ready(function(){
$('#jqgrid').jqGrid({
datatype: 'local',
data: mydata,
jsonReader: {
repeatitems : false,
},
caption: 'Titlepage Parameters',
colNames: ['title', 'color','fontsize'],
colModel: [
{name: 'config.titlepage.title'},
{name: 'config.titlepage.color'},
{name: 'config.titlepage.fontsize'},
],
});
});
JSON via URL (no data displayed). The file mydata.json contains the same data
that is used above, but in a local file instead of in the actual js code:
jQuery(document).ready(function(){
$('#jqgrid').jqGrid({
url:'mydata.json',
datatype:"json",
jsonReader: {
repeatitems : false,
},
caption: 'Titlepage Parameters',
colNames: ['title', 'color','fontsize'],
colModel: [
{name: 'config.titlepage.title'},
{name: 'config.titlepage.color'},
{name: 'config.titlepage.fontsize'},
],
});
});
First of all I would fix a little your first version of working code. jsonReader will be not used if you use jsonReader. Instead of that it will be used localReader. Additionally I would recommend you always use native id values if the input data have such one. So I would fix the code to the following:
$(function () {
"use strict";
var mydata = [
{
"_id": {"$oid": "50a3f962b7718da1a3090fa9"},
"config": {
"titlepage": {
"title": "My First Title",
"color": true,
"fontsize": "42/44"
}
}
},
{
"_id": {"$oid": "50a3f962b7718da1a3090faa"},
"config": {
"titlepage": {
"title": "My Second Title",
"color": true,
"fontsize": "42/44"
}
}
}
];
$('#jqgrid').jqGrid({
datatype: 'local',
data: mydata,
caption: 'Titlepage Parameters',
gridview: true,
height: 'auto',
colNames: ['title', 'color', 'fontsize'],
colModel: [
{name: 'config.titlepage.title' },
{name: 'config.titlepage.color' },
{name: 'config.titlepage.fontsize' },
],
localReader: {
id: "_id.$oid"
}
});
});
See the first demo.
In case of usage datatype: "json" you need to fix the jsonReader:
$(function () {
"use strict";
$('#jqgrid').jqGrid({
datatype: 'json',
url: 'Tim2.json',
caption: 'Titlepage Parameters',
gridview: true,
height: "auto",
//colNames: ['title', 'color', 'fontsize'],
colModel: [
{name: 'title', jsonmap: 'config.titlepage.title' },
{name: 'color', jsonmap: 'config.titlepage.color' },
{name: 'fontsize', jsonmap: 'config.titlepage.fontsize' },
],
jsonReader: {
repeatitems: false,
id: "_id.$oid",
root: function (obj) {
return obj;
}
}
});
});
See another demo.
Oleg's answer is the full solution.
Here is the modified code which works. That is, the code I originally wrote plus the one change (from Oleg) that successfully loaded the data into the grid. The key for me was to add the root function in jsonReader:
jQuery(document).ready(function(){
$('#jqgrid').jqGrid({
url:'mydata.json',
datatype:"json",
jsonReader: {
root: function (obj) { return obj; },
repeatitems : false,
},
caption: 'Titlepage Parameters',
colNames: ['title', 'color','fontsize'],
colModel: [
{name: 'config.titlepage.title'},
{name: 'config.titlepage.color'},
{name: 'config.titlepage.fontsize'},
],
});
});

jquerygrid with asp.net mvc razor view engine

I'm trying to follow this example on Phil haak's blog using the razor viewengine.
Except my view renders the json as text instead of displaying the grid.
Here is the code for my view :
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<script src="../../Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData/',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'Votes', 'Title'],
colModel: [
{ name: 'Id', index: 'Id', width: 40, align: 'left' },
{ name: 'Votes', index: 'Votes', width: 40, align: 'left' },
{ name: 'Title', index: 'Title', width: 400, align: 'left'}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/scripts/themes/coffee/images',
caption: 'My first grid'
});
});
</script>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
The rendered page looks like this :
{"total":3,"page":1,"records":22,"rows":[{"i":37,"cell":["37","1","What does AcceptVerbs do?"]},{"i":36,"cell":["36","1","Can I change the default model binder?"]},{"i":35,"cell":["35","1","How do I do custom paging?"]},{"i":34,"cell":["34","1","Writing a custom ControllerFactory"]},{"i":33,"cell":["33","65","How do I defend against CSRF attacks?"]},{"i":32,"cell":["32","2","If there was a random question generator, would you use it?"]},{"i":30,"cell":["30","51","Is there a random question generator?"]},{"i":29,"cell":["29","2","How many questions are in this table?"]},{"i":28,"cell":["28","7","How do I use the SelectList?"]},{"i":27,"cell":["27","50","How do I use jQuery grid with MVC"]}]}

jgGrid not displaying json data

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"]}]}