jqgrid loading on Button Click - jqgrid

Jqgrid load with data on pageload. When I try to load the grid on a button click grid load with the data but in the next moment the full grid get disappear if I use the grid on a content page with master page and the rows get disappear if I use a page without master page. Is there any solution for this? Thanks
Added a demo
Note: grid is disappearing on every postback
When I removed the update panel from master page , grid is not disappearing but the data on the grid is disappering
jQuery("#jqgItemDetails").jqGrid({
url: '',
datatype: "local",
colNames: ['UPC Code', 'OLD UPC', 'Item Description', 'Old Item Desc', 'Size UOM', 'Old Size UOM', 'Department', 'Category',
'Tax Description', 'WIC/CVV', 'Label', 'Last Movement', 'Last Purchase', 'Item Added', 'Comment', 'Store Number'],
colModel: [
{ name: 'UPC_Code', index: 'UPC_Code', width: 90, stype: 'text' },
{ name: 'UPC_Code_Old', index: 'UPC_Code_Old', width: 90, stype: 'text', hidden: true },
{ name: 'Item_Desc', index: 'Item_Desc', width: 150 },
{ name: 'Item_Desc_Old', index: 'Item_Desc_Old', width: 150, hidden: true },
{ name: 'Size_UOM', index: 'Size_UOM', width: 60 },
{ name: 'Size_UOM_Old', index: 'Size_UOM_Old', width: 60, hidden: true },
{ name: 'Department', index: 'Department', width: 100 },
{ name: 'Category', index: 'Category', width: 80 },
{ name: 'Tax_Desc', index: 'Tax_Desc', width: 150 },
{ name: 'WIC_CVV', index: 'WIC_CVV', width: 80 },
{ name: 'Label', index: 'Label', width: 150 },
{ name: 'Last_Movement', index: 'Last_Movement', width: 100 },
{ name: 'Last_Purchase', index: 'Last_Purchase', width: 100 },
{ name: 'Item_Added', index: 'Item_Added', width: 100 },
{ name: 'Comment', index: 'Comment', width: 100, editable: true },
{ name: 'Store_Number', index: 'Store_Number', width: 100, hidden: true }
],
multiselect: true,
rowNum: 10,
sortname: 'UPC_Code',
viewrecords: true,
sortorder: "desc",
pager: '#pager2',
width: 1100,
cellEdit: true,
cellsubmit: 'clientArray',
editurl: '',
height: 60,
onSelectRow: editRow,
shrinkToFit: false,
afterSaveCell: function (rowid, name, val, iRow, iCol) {
var grid = $("#jqgItemDetails");
if (name == 'Comment') {
grid.jqGrid('setCell', rowid, 'Comment', val);
}
},
caption: '<span style="height:20px;color:#cc961a">UPC Item Details</span>'
});
var lastSelection;
function editRow(id) {
if (id && id !== lastSelection) {
var grid = $("#jqgItemDetails");
grid.jqGrid('restoreRow', lastSelection);
grid.jqGrid('editRow', id, { keys: true });
lastSelection = id;
}
}
function btnUPCShow_OnClientClick() {
fillUPCDetailsGrid();
}
function fillUPCDetailsGrid() {
var UPCCol = new Array();
var UPCData = "", UPCLike = "", RangeFrom = "", RangeTo = "", FilterVal;
FilterVal = document.getElementById('ddlFilter').value;
if (FilterVal == 1) {
UPCData = document.getElementById('txtUPC').value; // '77098103440,77098103450,77098103470,77098104423'; // document.getElementById('txtUPC').value;
UPCCol = UPCData.split(',');
}
else if (FilterVal == 2) {
UPCLike = document.getElementById('txtUPC').value;
}
else if (FilterVal == 3) {
RangeFrom = document.getElementById('txtUPC').value;
RangeTo = document.getElementById('txtRangeTo').value;
}
$.ajax({
type: "POST",
url: 'ItemInquiries.aspx/GetUPCDetails',
data: JSON.stringify({ UPCCollection: UPCCol, UPCLike: UPCLike, UPCRangeFrom: RangeFrom, UPCRangeTo: RangeTo, Filter: FilterVal }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
var myjsongrid = $.parseJSON(Result.d);
for (var i = 0; i < myjsongrid.Table.length; i++) {
jQuery('#jqgItemDetails').jqGrid('addRowData', i + 1, myjsongrid.Table[i]);
}
}
});
}

Related

how to filter record from jqGrid using html dropdown using id

i am using jqgrid and i am to filter record from combo data is loaded from database .enter image description here
Screen 1
Controler
public JsonResult Getlist(int id,int LstatusId, bool AllDate,string DateFrom,string DateTo)
{
List<leadMaster> lmasterRecords = new List<leadMaster>();
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SP_leadMasterDetail", con))
{
if (clsCommon._UserType == "A")
cmd.Parameters.AddWithValue("#AgentID", id);
else
cmd.Parameters.AddWithValue("#AgentID", clsCommon._AgentID);
cmd.Parameters.AddWithValue("#LeadStatusID",LstatusId);
cmd.Parameters.AddWithValue("#AllDates",AllDate);
cmd.Parameters.AddWithValue("#DateFrom",DateFrom);
cmd.Parameters.AddWithValue("#DateTo",DateTo);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
lmasterRecords.Add(
new leadMaster
{
RecordID = Convert.ToInt64(reader.GetValue(0)),
Name = reader.GetString(1),
CityName = reader.GetString(2),
CountryName=reader.GetString(3),
Address=reader.GetString(4),
PhoneNo=reader.GetString(5),
MobileNo=reader.GetString(6),
Email=reader.GetString(7),
EnteryDate = reader.GetDateTime(8).ToShortDateString(),
ProfType=reader.GetString(9),
LeadStatus=reader.GetString(10),
ProjName=reader.GetString(11),
UnitTypeName=reader.GetString(12),
Description=reader.GetString(13),
User_name=reader.GetString(14),
IsClose=reader.GetString(15)
}
);
}
}
}
return Json(lmasterRecords, JsonRequestBehavior.AllowGet);
}
DropDown boxs
Filter By Agent:
#Html.DropDownList("var1", null, new { #class = "form-control col-sm-3 " })
JqGrid Function
script>
$.noConflict();
jQuery(document).ready(function ($) {
$("#jqGrid").jqGrid({
url: '#Url.Action("Getlist")',
datatype: 'json',
mtype: 'Get',
page: 1,
postData: { id: $("#var1").val(), LstatusId: $("#var2").val(), AllDate: $("#AllData").attr("checked") ? true : false, DateFrom: $("#cmbSDate").val(), DateTo: $("#cmbTDate").val() },
colModel: [
{ label:'RecordID', hidden: true, name: 'RecordID', key: true, width: 75 },
{ label: 'Name', name: 'Name', width: 200 },
{ label: 'CityName', name: 'CityName', width: 110 },
{ label: 'CountryName', hidden: true, name: 'CountryName', width: 150 },
{ label: 'Address', hidden: true, name: 'Address', width: 150 },
{ label: 'PhoneNo', hidden: true, name: 'PhoneNo', key: true, width: 75 },
{ label: 'MobileNo', name: 'MobileNo', width: 110 },
{ label: 'Email', name: 'Email', width: 200 },
{ label: 'Fax', hidden: true, name: 'Fax', width: 150 },
{ label: 'LeadDate', name: 'EnteryDate', width: 100 },
{ label: 'ProfType', hidden: true, name: 'ProfType', width: 150 },
{ label: 'LeadStatus', name: 'LeadStatus', key: true, width: 150 },
{ label: 'Description', name: 'Description', width:110 },
{ label: 'UnitTypeName', name: 'UnitTypeName', width: 150 },
{ label: 'User_name', name: 'User_name', width: 150 },
{ label: 'IsClose', name: 'IsClose', width: 50}],
loadonce:true,
viewrecords: true,
width: 1050,
height: 350,
rowNum: 100,
rowList: [10, 20, 30,50,100,500],
pager: "#jqGridPager"
});
});
</script>

How to save/restore the CheckBox state in jqGrid across webMethod?

I am using jqGrid with "multiselect: true" and webMethods. I need to persist state, so I am going to put the Grid state in the DB, in order to do this I need to know which rows have selected checkboxes and pass that through the webMethod, then on the other side I need to be able to specify to the Grid to select or unselect a particular checkbox.
This is my current binding code, serializeGridData doesn't pick up the checkbox state.
$(document).ready(function () {
jQuery("#selectedInmateList").jqGrid({
url: "<%= AdminPath %>WebMethods/WebService1.asmx/GetUsersJSON3",
postData: {
inmateList: function () {
return InmateListArg;
}
},
mtype: 'POST',
datatype: 'json',
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (postData) {
var propertyName, propertyValue, dataToSend = {};
for (propertyName in postData) {
if (postData.hasOwnProperty(propertyName)) {
propertyValue = postData[propertyName];
if ($.isFunction(propertyValue)) {
dataToSend[propertyName] = propertyValue();
} else {
dataToSend[propertyName] = propertyValue
}
}
}
return JSON.stringify(dataToSend);
},
onSelectRow: function (id) {
},
jsonReader: {
root: "d.rows",
page: "d.page",
total: "d.total",
records: "d.records"
},
colNames: ['select', 'LastName', 'FirstName', 'id'],
colModel: [
{ name: 'select', index: 'select', width: 300, align: 'center' },
{ name: 'LastName', index: 'LastName', width: 300, align: 'center' },
{ name: 'FirstName', index: 'FirstName', width: 300, align: 'center' },
{ name: 'id', index: 'id', align: 'center', hidden: true }
],
pager: '#prod_pager',
rowList: [10, 20, 30],
sortname: 'Code',
sortorder: 'desc',
rowNum: 10,
loadtext: "Loading....",
shrinkToFit: false,
multiselect: true,
emptyrecords: "No records to view",
//width: x - 40,
height: "auto",
rownumbers: true,
//subGrid: true,
caption: 'Selected Inmates'
});
});
If I understand your correctly you need first of all to send the current list of selected rows to the server. For example if the user select or unselect new row you can send the current list of the rows directly to the server. You can do this inside of onSelectRow and onSelectAll callbacks. Additionally you need that the server send you back only the data of the current page (the full data if you use loadonce: true option), but the list of ids of the rows which need be selected too. Inside of loadComplete you can call in the loop setSelection method to select the rows.
I would recommend you to examine the code of the callback onSelectRow, onSelectAll and loadComplete of the demo created for the answer. The old answer provide the basis of the same idea.
To pass the selected row IDs into the webMethod I used this:
var selectedIDs = jQuery('#selectedInmateList').jqGrid('getGridParam', 'selarrrow');
Then I added that to my webMethod param 'InmateListArg'
Then I added a hidden column which indicated if the row should be checked or not, then I used the loadComplete event to select the desired row based on the data in the hidden column.
$(document).ready(function () {
jQuery("#selectedInmateList").jqGrid({
url: "<%= AdminPath %>WebMethods/WebService1.asmx/GetUsersJSON3",
postData: {
inmateList: function () {
return InmateListArg;
}
},
mtype: 'POST',
datatype: 'json',
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (postData) {
var propertyName, propertyValue, dataToSend = {};
for (propertyName in postData) {
if (postData.hasOwnProperty(propertyName)) {
propertyValue = postData[propertyName];
if ($.isFunction(propertyValue)) {
dataToSend[propertyName] = propertyValue();
} else {
dataToSend[propertyName] = propertyValue
}
}
}
return JSON.stringify(dataToSend);
},
onSelectRow: function (id) {
},
loadComplete: function (id) {
idsOfSelectedRows = [];
var gridData = jQuery("#selectedInmateList").getRowData();
for (i = 0; i < gridData.length; i++) {
var isChecked = gridData[i]['checked'];
var id = gridData[i]['id'];
if (isChecked == 'True') {
idsOfSelectedRows.push(id);
}
}
var $this = $(this), i, count;
for (i = 0, count = idsOfSelectedRows.length; i < count; i++) {
$this.jqGrid('setSelection', idsOfSelectedRows[i], false);
}
},
jsonReader: {
root: "d.rows",
page: "d.page",
total: "d.total",
records: "d.records"
},
colNames: ['select', 'LastName', 'FirstName', 'id', 'checked'],
colModel: [
{ name: 'select', index: 'select', width: 300, align: 'center' },
{ name: 'LastName', index: 'LastName', width: 300, align: 'center' },
{ name: 'FirstName', index: 'FirstName', width: 300, align: 'center' },
{ name: 'id', index: 'id', align: 'center' /*, hidden: true*/ },
{ name: 'checked', index: 'checked', align: 'center' }
],
pager: '#prod_pager',
rowList: [10, 20, 30],
sortname: 'Code',
sortorder: 'desc',
rowNum: 10,
loadtext: "Loading....",
shrinkToFit: false,
multiselect: true,
emptyrecords: "No records to view",
//width: x - 40,
height: "auto",
rownumbers: true,
//subGrid: true,
caption: 'Selected Inmates'
});
jQuery("#prodgrid").jqGrid('navGrid', '#prod_pager',
{ edit: false, add: false, del: true, excel: true, search: false });
});

JQGRID Performance issues

My Jqgrid is freezing after 500 rows, page is blocking and if rows exceeds 1000 or 1500 then one browser alert is coming and saying that "long time to execute script .. do you wanna stop or continue.. " I am in no mans land can you please check my code and suggest me.. Am I doing any wrong.
one more issue is Why my loading GIF image and page stuck until all rows loaded?
$(document).ready(function ()
{
GetTrackOrdersData();
});
var searchFilter = {};
searchFilter.REFERENCE = "%";
searchFilter.INVOICENOR = "";
searchFilter.PRODNAME = "ALL";
searchFilter.ORDSTATUS = "WIP";
------etc ------
function GetTrackOrdersData()
{
var param = JSON.stringify(
{
'searchFilter': searchFilter
}); //This function is from JSon2.js
$.ajax(
{
type: "POST",
url: "TrackOrdersNew.aspx/GetTrackOrdersData",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (mydata)
{debugger;
var mydata = $.parseJSON(mydata.d);
if (mydata != null && mydata.length == 0)
{
$('#divgrid').hide();
$('#gbox_list1').hide();
$("#jqgridWrapperdiv").hide();
alert('No Records');
}
else if(mydata != null)
{
var i = 0;
for (i; i <= mydata.length; i++)
{
jQuery("#list1").jqGrid('addRowData', i + 1, mydata[i]);
}
if (i > 0)
{
$('.ui-jqgrid-title').text('Track Orders (' + (i - 1) + ')');
}
$("#jqgridWrapperdiv").hide();
$('#divgrid').show();
}
},
error: function (mydata)
{
alert("Some thing went wrong because of network. Please reload the page. Code:100T"+mydata.responseText);
$('#divgrid').hide();
},
complete: function ()
{
$("#jqgridWrapperdiv").hide();
}
});
}
function bindGrid()
{
jQuery("#list1").jqGrid(
{
datatype: "local",
colNames: ['Customer', 'Delivery', 'TrackNo','Ref', 'JobNo', 'Type', 'Product', 'Status',
'EntryDate', 'Scheduled', 'Invoiced'
],
colModel: [
{
name: 'CUOH_CUST_CD',
index: 'CUOH_CUST_CD',
width: 100,
classes: 'pointer'
},
{
name: 'CUOA_DEL_CUST_CD',
index: 'CUOA_DEL_CUST_CD',
width: 69,
classes: 'pointer'
},
{
name: 'CUOH_TRAK_NO',
index: 'CUOH_TRAK_NO',
width: 70,
classes: 'pointer'
},
{
name: 'CUOH_SOURCE_REF',
index: 'CUOH_SOURCE_REF',
width: 70,
classes: 'pointer'
},
{
name: 'CUOH_JOB_NO',
index: 'CUOH_JOB_NO',
width: 60,
classes: 'pointer'
},
{
name: 'CUOH_ORDER_TYPE',
index: 'CUOH_ORDER_TYPE',
width: 65,
classes: 'pointer'
},
{
name: 'CUOL_DESCR_LOC',
index: 'CUOL_DESCR_LOC',
width: 155,
classes: 'pointer'
},
{
name: 'Status',
index: 'Status',
width: 100,
classes: 'pointer',
cellattr: function (rowId, value)
{
// additional parameter of cellattr: rawObject, cm, rdata are optional
if (value.indexOf("ompleted")!=-1)
{
return ' class="bcolor"';
}
}
},
{
name: 'CUOH_ENTRY_DATE_TIME',
index: 'CUOH_ENTRY_DATE_TIME',
formatter: 'date',
formatoptions:
{
srcformat: 'd/m/Y',
newformat: 'd/m/Y'
},
width: 77,
classes: 'pointer'
},
{
name: 'CUOH_SCHEDULE_DATE',
index: 'CUOH_SCHEDULE_DATE',
formatter: 'date',
formatoptions:
{
srcformat: 'd/m/Y',
newformat: 'd/m/Y'
},
width: 84,
classes: 'pointer'
},
{
name: 'CUOH_INVOICE_DATE_TIME',
index: 'CUOH_INVOICE_DATE_TIME',
formatter: 'date',
formatoptions:
{
srcformat: 'd/m/Y',
newformat: 'd/m/Y'
},
width: 72,
classes: 'pointer'
}],
//multiselect: true,
//rowList: [10, 20, 30, 40],
//pager: jQuery('#pager1'),
//rowList: [], // disable page size dropdown
//pgbuttons: false, // disable page control like next, back button
//pgtext: null, // disable pager text like 'Page 0 of 10'
//viewrecords: true, // disable current view record text like 'View 1-10 of 100'
rowNum: 10000,
sortorder: "asc",
caption: "Track Orders",
gridview: true,
//shrinkToFit: true,
loadui:"block",
loadonce: true,
rownumbers: true, //Displays Row number Column
onSelectRow: function (rowId)//ondblClickRow
{
var rowData = jQuery(this).getRowData(rowId);
var trackingNo = rowData['CUOH_TRAK_NO'];
RowClicked(trackingNo);
}
});
}
C sharp:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetTrackOrdersData(TrackOrdersFilterData searchFilter)
{
if (HttpContext.Current.Session["LoginName"] == null)
{
HttpContext.Current.Response.Redirect("~/Login.aspx");
}
string val = string.Empty;
DataSet ds = GetTrackOrders(searchFilter);
if (ds.Tables.Count > 0)
{
val = DataTableToJSON(ds.Tables[0]);
}
return val;
}

jqSubGrid not loading with data

I do realize many have asked this same question. I have tried all other suggestions and have had no success. I know for sure its something I am overlooking and wanted a second set of eyes to help me. Thanks in advance!!
My problem is that the primary grid loads find. Its the sub grid thats the problem.
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#PositionsGrid").jqGrid({
url: '/Position/GetPositions?projectid=#Model.ID',
datatype: 'json',
mtype: 'POST',
colNames: ['PositionID', 'ID', 'Job', 'Band', 'Start Date', 'End Date','Current Assignee','Terminated Worker','Status'],
colModel: [
{ name: 'PositionID', index: 'PositionID', width: 20, align: 'left', hidden: true, sortable: false, search: false,key:true },
{ name: 'DisplayID', index: 'DisplayID', width: 50, align: 'left' },
{ name: 'JobTitle', index: 'JobTitle', width: 100, align: 'left' },
{ name: 'Band', index: 'Band', width: 50, align: 'left' },
{ name: 'StartDate', index: 'StartDate', width: 50, align: 'left', searchoptions: { sopt: ['cn'], dataInit: datePick} },
{ name: 'EndDate', index: 'EndDate', width: 50, align: 'left', searchoptions: { sopt: ['cn'], dataInit: datePick} },
{ name: 'CurrentWorker', index: 'CurrentWorker', width: 100, align: 'left' },
{ name: 'TerminatedWorker', index: 'TerminatedWorker', width: 100, align: 'left' },
{ name: 'Status', index: 'Action', width: 50, align: 'left', search: false}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'PositionID',
sortorder: "asc",
viewrecords: true,
autowidth: true,
subGrid: true,
subGridRowExpanded: showDetails
});
$('#PositionsGrid').jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
$("#PositionGrid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false, refresh: true });
});
datePick = function (elem) {
$(elem).datepicker({ dateFormat: "mm/dd/yy", onSelect: function (dateText, inst) { $("#grid")[0].triggerToolbar(); } });
};
function showDetails(subgrid_id, row_id) {
showSubGrid_AssignmentsGrid(subgrid_id, row_id, "<br><b>Worker History</b><br><br>", "AssignmentsGrid");
}
function showSubGrid_AssignmentsGrid(subgrid_id, row_id, message, suffix) {
var subgrid_table_id;
subgrid_table_id = subgrid_id + "_t";
if (message) jQuery('#' + subgrid_id).append(message);
if (message) jQuery('#' + subgrid_id).append(message);
jQuery("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table>");
jQuery("#" + subgrid_table_id).jqGrid({
url: "Position/GetAssignmentsByPosition?positionid=" + row_id,
datatype: "json",
colNames: ['AssignID', 'JobReqNum', 'WorkerName', 'StartDate', 'EndDate','Status'],
colModel: [
{ name: "AssignID", index: "AssignID", width: 80},
{ name: "JobReqNum", index: "JobReqNum", width: 130 },
{ name: "WorkerName", index: "WorkerName", width: 80, align: "right" },
{ name: "StartDate", index: "StartDate", width: 80, align: "right" },
{ name: "EndDate", index: "EndDate", width: 100, align: "right" },
{ name: "Status", index: "Status", width: 100, align: "right" }
],
height: '100%',
rowNum: 20,
sortname: 'AssignID',
sortorder: "asc"
});
}
</script>
the controller action that loads the subgrid is below
public JsonResult GetAssignmentsByPosition(int positionid)
{
ProjPosition position = uow.PositionRepository.GetPosition(positionid);
var jsonRows = position.ProjPositionAssignments.AsEnumerable()
.Select(a => new
{
cell = new string[] { a.ID.ToString(),
a.JobReqNum == null ? "" :a.JobReqNum,
a.Worker == null ? "" : a.Worker.FullName,
(a.StartDate == null) ? "" : ((DateTime)a.StartDate).ToString("MM/dd/yyyy"),
(a.EndDate == null) ? "" : ((DateTime)a.EndDate).ToString("MM/dd/yyyy"),
(a.Status == null ? "Active" : StatusDictionary.AssignmentStatusDictionary[a.Status])
}
})
.ToArray();
var jsonData = new
{
rows = jsonRows
};
return Json(jsonData);
}
You also need to pass to jqgrid:
page = numberOfPages
records = totalRecords,
I personally use something like:
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
rows = (
from item in pagedQuery
select new
{
cell = new string[] {
item.value1,
item.value2, ....
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);

How to properly set the jsonReader of a jqGrid to handle string array of rows

Here are my column and model items:
var col_names = ['Qty', 'SFC', 'Item Nbr', 'Brand', 'Product', 'Supplier', 'Price', 'UOM', 'Case', 'Remarks', 'Weight', 'Par', 'Sort', 'Purchased', 'ProductId'];
var col_model = [
{ name: 'Quantity', index: 'Quantity', width: 22, sorttype: "number", editable: true, edittype: 'text', editoptions: { size: 10, maxlength: 15} },
{ name: 'ProductAttributes', index: 'ProductAttributes', width: 50 },
{ name: 'ItemNum', index: 'ItemNum', width: 50, align: "right"},
{ name: 'BrandName', index: 'BrandName', width: 100 },
{ name: 'ProducName', index: 'ProducName', width: 150 },
{ name: 'SupplierName', index: 'SupplierName', width: 100 },
{ name: 'Price', index: 'Price', width: 40, sorttype: "number", align: "right" },
{ name: 'UOM', index: 'UOM', width: 30 },
{ name: 'CasePack', index: 'CasePack', width: 30 },
{ name: 'PackageRemarks', index: 'PackageRemarks', width: 80 },
{ name: 'AveWeight', index: 'AveWeight', width: 33, align: "right" },
{ name: 'Par', index: 'Par', width: 20, align: "right", editable: true, edittype: 'text', editoptions: { size: 10, maxlength: 15} },
{ name: 'SortPriority', index: 'SortPriority', hidden: true },
{ name: 'LastPurchaseDate', index: 'LastPurchaseDate', width: 50, align: "right" },
{ name: 'ProductId', index: 'ProductId', hidden: true, key: true },
];
here's the grid initialization
favoriteGrid = $('#favoriteGrid');
favoriteGrid.jqGrid({
url: '/xxx/yyy/zzz/',
datatype: 'json',
ajaxGridOptions: { contentType: "application/json" },
jsonReader: {
id: "ProductId",
cell: "",
root: function (obj) { return obj.rows; },
page: function () { return 1; },
total: function () { return 1; },
records: function (obj) { return obj.rows.length; },
repeatitems: false
},
colNames: col_names,
colModel: col_model,
pager: $('#favoritePager'),
pginput: false,
rowNum: 1000,
autowidth: true,
sortable: true, // enable column sorting
multiselect: true, // enable multiselct
gridview: true,
ignoreCase: true,
loadonce: true, // one ajax call per
loadui: 'block',
loadComplete: function () {
fixGridHeight(favoriteGrid);
},
ondblClickRow: function (rowid, ri, ci) {
},
onSelectRow: function (id) {
if (id && id !== lastSel) {
favoriteGrid.restoreRow(lastSel);
lastSel = id;
}
favoriteGrid.editRow(id, true);
},
gridComplete: function () {
}
}).jqGrid('navGrid', '#favoritePager',
{ add: false, edit: false, del: false, search: true, refresh: false },
{},
{},
{},
{ multipleSearch: true, showQuery: false },
{}).jqGrid('sortableRows').jqGrid('gridDnD');
and finally, the data:
{"rows":[["1",null,"342240"," ","15 AMP, 600V, TIME DELAY, CLASS G","Home Depot - Canada","3.83","EA","1","- 15A, 600V - Class G - Mfg #SC-15","0.02","","0",null,"2977175133"],["1",null,"3573375","NEWPRT","STEAK TOP SIRLOIN CH CC 8OZ","SYSCO","6.875","LB","24 PK","8 OZ","24 LB","","0",null,"1675949601"],["1",null,"201805"," ","GE-HOTPOINT DISHWASHER UPPER RACK","Home Depot - Canada","54.43","EA","1","Dishwasher Upper Rack - Fits Models #HDA2000, HDA2100 And GSD2100 - Mfg #WD28X10011","6.5","","0",null,"2977172115"],["1",null,"286044"," ","GE DISHWASHER SILVERWARE BASKET","Home Depot - Canada","19.19","EA","1","Silverware Basket - Mfg #WD28X265","0.06","","0",null,"2977172688"]]}
I get the right number of rows and the columns but no data is displayed in the grid, if that makes sense.
Just for completeness:
[HandleJsonException]
public JsonResult ProductGroupService(Int64 id = 0)
{
var q = Repository.GetFavoriteProducts(SimpleSessionPersister.User.Id, id).ToArray();
var result = (from fp in q
select new string[]
{
Convert.ToString(fp.Quantity),
fp.ProductAttributes,
fp.ItemNum,
fp.BrandName,
fp.ProducName,
fp.SupplierName,
Convert.ToString(fp.Price),
fp.UOM,
fp.CasePack,
fp.PackageRemarks,
fp.AveWeight,
Convert.ToString(fp.Par),
Convert.ToString(fp.SortPriority),
fp.LastPurchaseDate,
Convert.ToString(fp.ProductId)
}).ToArray();
var jsonData = new
{
rows = result
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Thank you,
Stephen
You main problem is that you used repeatitems: false property of the jsonReader which is wrong for your input.
Moreover you should remove trailing comma at the end of definition of col_model. The error will be ignored by many modern browsers, but not for the old one.
After the changed the grid will be successfully loaded: see the demo.

Resources