On First load of jqgrid how to load page of specific record? - jqgrid

Using Jquery.Jqgrid v4.4.4
I have 10 pages in my State grid, i want to display the page which holds state name 'Tamilnadu' on first of the jqgrid loads. Not to bring the state on the first page, need to display that page on the first time.
EDIT: My Jqgrid code, here i have 'State' column contains 10+ pages , in one of the page 'Tamilnadu' state record is there. Please help me on how to load the grid with that page on first load.
// Setting up County Grid properties
$(function () {
$("#CountyGrid").jqGrid({
url: '/ControlTables/GetCountyResult',
datatype: "json",
contentType: "application/json; charset-utf-8",
mtype: 'Get',
colNames: ['CountyIdentifier', 'Active', 'State', 'County', 'County Number', AddNewBtn],
colModel: [
{
Key: true, name: 'CountyIdentifier', index: 'CountyIdentifier', width: 16, editable: false, sortable: true, align: "left", classes: "grid-col",
hidden: true, displayName: "CountyIdentifier"
},
{
name: 'ActiveFlag', index: 'ActiveFlag', width: 4, align: 'center', editable: true,
edittype: 'checkbox', editoptions: { value: "True:False", defaultValue: "True" }, formatter: "checkbox", displayName: "Active"
},
{
name: 'StateIdentifier', index: 'StateIdentifier', editable: true, formatter: 'select', sortable: true,
edittype: 'select', width: 19, align: "left", classes: "grid-col", editoptions: { style: "height:23px;" }, displayName: "State", valueField: "StateText",
},
{
name: 'CountyText', index: 'CountyText', width: 19, editable: true, sortable: true, align: "left", classes: "grid-col",
editoptions: { style: "height:23px;", maxlength: "48", dataInit: function (el) { $(el).css('text-transform', 'uppercase'); } }, displayName: "County"
},
{
name: 'CountyNumber', index: 'CountyNumber', width: 7, editable: true, sortable: true, align: "left", classes: "grid-col",
editoptions: { style: "height:23px;", maxlength: "5" }, displayName: "County Number"
},
{
name: "action", index: "action", sortable: false, editable: false, align: "center", width: "7", displayName: "Action"
},
],
// Call select row function
onSelectRow: function (id) {
if (onPagingLastSel) {
$('#CountyGrid').jqGrid('resetSelection', lastsel, true);
onPagingLastSel = false;
}
rowSelect(id);
},
onPaging: function () {
//Prompt to save pending changes when the user try to navigate Next/Previous/Front/Last page.
if (lastsel != null) {
$('#CountyGrid').jqGrid('saveRow', lastsel, {});
var editrowData = jQuery("#CountyGrid").getRowData(lastsel);
var editRow_ActiveFlag = editrowData['ActiveFlag']
var editRow_StateIdentifier = editrowData['StateIdentifier']
var editRow_CountyText = editrowData['CountyText']
var editRow_CountyNumber = editrowData['CountyNumber']
$('#CountyGrid').jqGrid('editRow', lastsel, {});
if ((lastsel_StateIdentifier != editRow_StateIdentifier && editRow_StateIdentifier != undefined)||
(lastsel_CountyText != editRow_CountyText && editRow_CountyText != undefined) ||
(lastsel_CountyNumber != editRow_CountyNumber && editRow_CountyNumber != undefined) ||
(lastsel_ActiveFlag != editRow_ActiveFlag && editRow_ActiveFlag != undefined)) {
DialogConfirmSave("GENL-002");
onPagingLastSel = true;
return 'stop';
}
else {
lastsel = null;
//enable New Button
$("#NewBtnId").removeClass('add-new-button-disable');
$("#NewBtnId").removeAttr("disabled");
}
}
},
// load all States into jqGrid dropdown
beforeProcessing: function (response) {
var $self = $(this),
options = response.colModelOptions, StateIdentifier;
if (options != null) {
for (StateIdentifier in options) {
if (options.hasOwnProperty(StateIdentifier)) {
$("#CountyGrid").jqGrid("setColProp", StateIdentifier, options[StateIdentifier]);
}
}
}
},
// Grid column header alignment to the left diable new button for general users
loadComplete: function () {
$("#CountyGrid").jqGrid("setLabel", "Active", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "StateIdentifier", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "CountyText", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "CountyNumber", "", { "text-align": "left" })
},
pager: jQuery('#CountyPager'),
rowNum: jqGridRowCount,
rowList: GridRowList,
viewrecords: true,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
multiselect: false,
autowidth: true,
height: 560,
hidegrid: false,
}).navGrid('#CountyPager', {
edit: false, add: false, del: false, search: false, refresh: false, reload: false, restoreAfterSelect: false
})
});
My Controller code:
public JsonResult GetCountyResult(string sidx, string sord, int page, int rows, bool getAllRecords = false)
{
objCountyViewModel = new CountyViewModel();
int totalRecords = 0;
if (Session["CountyList"] != null && Session["CountyList"] is List<CountyModel>)
{
objCountyViewModel.CountyModelList = (List<CountyModel>)Session["CountyList"];
if (objCountyViewModel.CountyModelList != null)
{
Session["CountyList"] = objCountyViewModel.SortCounty(sidx, sord);
totalRecords = objCountyViewModel.CountyModelList.Count();
}
}
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
rows = getAllRecords ? totalRecords : rows;
var jsonData = new
{
colModelOptions = new
{
StateIdentifier = new
{
formatter = "select",
edittype = "select",
editoptions = new
{
value = objCountyViewModel.GetStateDropdownList()
}
}
},
total = totalPages,
page,
records = totalRecords,
rows = objCountyViewModel.GetCountyPageList(page, rows)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}

Related

jqgrid inline editing autocomplete dropdown

Found answers in Oleg post but unable to solve in my case.
I have a jqGrid with inline editing. That works fine. One column 'SupervisorUserID' has a dropdown box with list of entries which retrieved from a database query already.
As the entries are too much, I want to have an input field which will autocomplete/search the dropdown list.
Please help me to achieve this. Thanks.
My code,
public JsonResult PersonnelManagementGrid(string sidx, string sord, int page, int rows)
{
objPersonnelManagementViewModel = new PersonnelManagementViewModel();
objPersonnelManagementViewModel.PersonnelManagementModelList = (List<PersonnelManagementModel>) Session["PersonnelList"];
var results = objPersonnelManagementViewModel.PersonnelManagementModelList.Select(x => new
{
x.UserID,
x.Name,
x.InActive,
x.SupervisorUserID,
});
int pageIndex = Convert.ToInt16(page) - 1;
int pageSize = rows;
int totalRecords = results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{ results = results.OrderByDescending(e => e.Name); }
else { results = results.OrderBy(e => e.Name); }
results = results.Skip(pageIndex * pageSize).Take(pageSize);
var sbLocations = new System.Text.StringBuilder();
Dictionary<string, string> personnelList = new Dictionary<string, string>();
personnelList = objPersonnelManagementViewModel.PersonnelManagementModelList.ToDictionary(x => x.UserID, x => x.Name);
//personnelList.Add("1","one");
//personnelList.Add("2", "two");
//personnelList.Add("3", "three");
foreach (var sortedLocation in personnelList)
{
sbLocations.Append(sortedLocation.Key);
sbLocations.Append(':');
sbLocations.Append(sortedLocation.Value);
sbLocations.Append(';');
}
if (sbLocations.Length > 0)
sbLocations.Length -= 1; // remove last ';'
var jsonResults = new
{
colModelOptions = new
{
SupervisorUserID = new
{
formatter = "select",
edittype = "select",
editoptions = new
{
value = sbLocations.ToString()
}
}
},
total = totalPages,
page,
records = totalRecords,
rows= results,
};
return Json(jsonResults, JsonRequestBehavior.AllowGet);
}
Jquery:
$(function () {
$("#PersonnelManagementGrid").jqGrid({
url: '/PersonnelManagement/PersonnelManagementGrid',
datatype: "json",
contentType: "application/json; charset-utf-8",
mtype: 'Get',
colNames: ['UserID', 'Name', 'Role', 'Active?', 'Supervisor', 'Change Active', 'Try Delete'],
colModel: [
{ key: true, name: 'UserID', index: 'UserID', hidden: true },
{
name: 'Name', index: 'Name', editable: false, width: "460", sortable: true,
},
{
name: 'Role', index: 'Role', editable: false, width: "200", sortable: true,
},
{
name: 'InActive', index: 'InActive', editable: false, width: "200", sortable: true,
},
{
name: 'SupervisorUserID', index: 'SupervisorUserID', editable: true, formatter: 'select', width: "200", sortable: true,
edittype: 'select', width: "200", align: "center",
},
{
name: "Change Active", sortable: false, width: "200", align: "center",
formatter: function (cellvalue, options, rowObj) {
var cBtn = '<input type="button" class="button" value="Change" onclick= "changeActive(' + "'" + rowObj.id + "','" + "values" + "','" + "values" + '\')"/>'
return cBtn;
}
},
{
name: "Try Delete", sortable: false, width: "200", align: "center",
formatter: function (cellvalue, options, rowObj) {
var cBtn = '<input type="button" value="Delete" onclick= "tryDelete(' + "'" + rowObj.id + "','" + "values" + "','" + "values" + '\')"/>'
return cBtn;
}
}
],
beforeProcessing: function (response) {
var $self = $(this),
options = response.colModelOptions, p;
if (options != null) {
for (p in options) {
if (options.hasOwnProperty(p)) {
$self.jqGrid("setColProp", p, options[p]);
}
}
}
},
pager: jQuery('#pager'),
rowNum: 15,
rowList: [5, 10, 15],
height: '100%',
width: '1328',
viewrecords: true,
caption: 'Personnel Management',
//loadonce: true,
emptyrecords: 'No records to display',
scrollerbar: false,
jsonReader: {
root: "rows",
page: "pagenumbers",
total: "totalnumbers",
records: "records",
repeatitems: false,
id: "0"
},
hidegrid: false,
multiselect: false,
onSelectRow: function (id) {
rowSelect(id);
},
}).navGrid('#pager', { edit: false, add: false, del: false, search: false, cancel: false, reload: false, refresh: false });
});

JqGrid paging with lots of grids

I have a single page ASP.Net web forms application. And lots of grids. In my application, there is some links to hide or show grids. The problem is, when i start the application, the pagination of the displayed grid is working properly. (I tried this for each grid). But when I Click the link for hide a grid and show another grid, paging does not working. The grid initialization is;
$('#tblApplicationSettings').jqGrid({
url: cms.util.getAjaxPage(),
cellLayout: cms.theme.list.cellLayout,
hoverrows: false,
forceFit: true,
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "",
id: "0"
},
width: 900,
height: 400,
datatype: 'local',
colNames: ['SettingId',
'Description',
'Name',
'Value',
'ServerId',
'IsReadOnly',
''
],
colModel: [
{
name: 'SettingId',
index: 'SettingId',
hidden: true
},
{
name: 'Description',
index: 'Description',
search: false,
editable: true,
sortable: false,
width: 150,
inlineEditable: true
},
{
name: 'Name',
index: 'Name',
search: false,
editable: false,
sortable: false,
width: 150,
inlineEditable: false
},
{
name: 'Value',
index: 'Value',
search: false,
editable: true,
sortable: false,
width: 250,
inlineEditable: true,
},
{
name: 'ServerId',
index: 'ServerId',
search: false,
editable: true,
sortable: false,
width: 150,
formatter: 'select',
edittype: 'select',
editoptions: {
value: options,
},
inlineEditable: true
},
{
name: 'IsReadOnly',
index: 'IsReadOnly',
hidden: true
},
{
name: 'JsUsage',
index: 'JsUsage',
search: false,
editable: true,
sortable: false,
width: 150,
inlineEditable: true
},
],
onSelectRow: function (id) {
if (id && id !== lastSelection) {
jQuery('#grid').jqGrid('restoreRow', lastSelection);
lastSelection = id;
}
var columnModel = $('#grid').getGridParam('colModel');
var colNames = new Array();
$.each(columnModel, function (index, column) {
colNames.push(column.name);
if (isReadOnly || !column.inlineEditable) {
column.editable = false;
}
else {
column.editable = true;
}
if (column.edittype == "select") {
column.editoptions.dataEvents = [{
type: 'change',
fn: function (e) {
var newServerId = $(this).val();
that.isServerIdChanged = true;
if (newServerId == "null") {
}
}
}]
}
});
var row = $('#grid').getRowData(id);
var isReadOnly = row.IsReadOnly == "true" ? true : false;
if (isReadOnly) {
alert("row is not editable");
return null;
}
jQuery("#grid").jqGrid('editRow', id, {
keys: true,
extraparam: {
dataType: 'updateSetting',
colNames: JSON.stringify(colNames),
settingName: row.Name,
settingId: row.SettingId
},
successfunc: function (result) {
$("#grid").trigger('reloadGrid');
}
});
},
editurl: '/Ajax.ashx',
rowNum: 25,
direction: "ltr",
scroll: 1,
gridview: true,
pager: '#divPager',
viewrecords: true,
});
$('#grid').setGridParam({ datatype: "json", postData: { dataType: 'getSettings' } });
$('#grid').jqGrid('navGrid', '#divPager', { edit: false, add: false, del: false, search: false, refresh: false });
$('#grid').trigger('reloadGrid');
like this for all grids. I need tips or helps. Thanks.

Sorting icon not updating on setting the sortorder

I am trying to change the sorting order of jqGrid by using this code:
jQuery('#id').setGridParam({sortorder:"desc"}).trigger("reloadGrid");
It changes the sortorder of the table but the Sorting Icon of the table is not changing as per the order. In onSortCol i'm sorting the column which actually sort the column. But when i use the above piece of code to set the sortorder, the sortorder is set but the sort icon still shows the previous sortorder.
_table.jqGrid({
datatype: 'local', // disable initial autoload. this will be when load function is called "json",
altRows: true,
altclass : 'AltRowClass',
gridView: true,
width:850,
height:"auto",
rowheight: 75,
align: 'center',
treeGrid: false,
loadonce:true,
ExpandColumn: 'name',
loadtext : 'Currently updating',
mtype : 'POST',
colNames: ['MSISDN','IMSI','Last name','First name','Device type','CE Index','Customer lifetime value'],
colModel: [
{ name: 'MSISDN', align: 'center', hidden: false, sortable: false,formatter: maskingColumn},
{ name: 'IMSI', align: 'center', hidden: false, sortable: false,formatter: maskingColumn},
{ name: 'LastName', align: 'center', hidden: false, sortable: false},
{ name: 'FirstName', align: 'center', hidden: false, sortable: false},
{ name: 'DeviceType', align: 'center', hidden: false, sortable: false,formatter: columnData},
{ name: 'CEIndex', align: 'center', hidden: false, sortable: true, sorttype: 'int'},
{ name: 'CustomerLifetimeValue', align: 'center', hidden: false, sortable: false}
],
sortname: 'CEIndex',
sortorder: 'desc',
loadComplete: function(data)
{
var rowCount = _table.jqGrid('getGridParam', 'records');
if (rowCount > 5) {
_table.parents("div.ui-jqgrid-bdiv").css({'max-height':'300px'});
_table.closest(".ui-jqgrid-bdiv").css({'overflow-y':'auto'}).css({'overflow-x':'hidden'});
}
if (rowCount != 0) {
_table.parents().find('.ui-jqgrid-view').first().show();
}
if (rowCount <= rowsNum) {
utils.find('cei-drill-customer-detail-showmore').hide();
} else {
utils.find('cei-drill-customer-detail-showmore').show();
}
_table.trigger("reloadGrid");
} ,
onSortCol: function (data, status, xhr) {
if (xhr == 'asc') {
var postData = this.p.postData.jsonRequest.replace('Top','Bottom');
actionInputObjectExportCustDrilldown.parameters.requestQuery = actionInputObjectExportCustDrilldown.parameters.requestQuery.replace('Top','Bottom');
var postDataVar = {
operation : 'drillDownLevel1',
drillLevel1 : "drilldown",
jsonRequest : postData
};
_this.load(postDataVar);
} else if (xhr == 'desc') {
var postData = this.p.postData.jsonRequest.replace('Bottom','Top');
actionInputObjectExportCustDrilldown.parameters.requestQuery = actionInputObjectExportCustDrilldown.parameters.requestQuery.replace('Bottom','Top');
var postDataVar = {
operation : 'drillDownLevel1',
drillLevel1 : "drilldown",
jsonRequest : postData
};
_this.load(postDataVar);
}
},
beforeProcessing : function(data, status, xhr) {
jQuery('div#jqgh_' + prefix + '-cei-dd-customer-details-table_CustomerLifetimeValue.ui-jqgrid-sortable').text("Customer Lifetime Value(" + filterValuesHl.currency + ")");
if (data.queryError != null || !data.rows || data.rows.length == 0) {
utils.find('cei-drill-customer-detail-ExportShowMore').hide();
utils.find('div-for-export-customer').hide();
var noError = utils.find('cei-customerDetails-div').parent().find(".cei-customer-details-dd-no-data");
if (data.queryError != null) {
noError.text("Error in portlet: " + data.queryError);
} else {
noError.html("<strong>No Data Available</strong>");
}
noError.show();
return false;
} else {
utils.find('cei-drill-customer-detail-ExportShowMore').show();
utils.find('div-for-export-customer').show();
utils.find('cei-drill-customer-detail-showmore').show();
//Hiding the columns which has no data in all the rows.
hideColumns(data);
//Setting CSV Data
csvData = data;
}
},
beforeRequest : function() {
_table.parents().find('.ui-jqgrid-view').first().hide();
utils.find('cei-customerDetails-div').parent().find(".cei-customer-details-dd-no-data").hide();
},
loadError : function(xhr, st, err) {
utils.find('cei-drill-customer-detail-ExportShowMore').hide();
utils.find('div-for-export-customer').hide();
var noError = utils.find('cei-customerDetails-div').parent().find(".cei-customer-details-dd-no-data");
noError.html("<html>Error connecting portlet: " + err + "</strong>");
noError.show();
}
});
You can try following code where id is your column name.
$('#grid').jqGrid('setGridParam', {sortorder: 'desc'});
$('#grid').jqGrid('sortGrid', 'id');

jqgrid apply filter after reload?

Am using jqgrid, loading data once, sorting and filtering locally and doing a refresh after each update/insert/delete. It works fine, besides that if I am using a filter (on top of grid), the filter remains the same after refresh, but the filter is not re-applied on the newly loaded data.
I have tried to call mygrid[0].triggerToolbar() after reloading grid with trigger('reloadGrid'), but there is no effect.
Thanks for any help or pointers :-)
Code below:
var lastsel;
var mygrid;
var currentLang;
//setup grid with columns, properties, events
function initGrid(lang, productData, resellerData, resellerSearchData) {
mygrid = jQuery("#list2").jqGrid({
//data loading settings
url: '/public/Gadgets/LinkGadget/ProductLinks/' + lang,
editurl: "/public/Gadgets/LinkGadget/Edit/" + lang,
datatype: "json",
mtype: 'POST',
jsonReader: {
root: "rows",
cell: "",
page: "currpage",
//total: "totalrecords",
repeatitems: false
},
loadError: function (xhr, status, error) { alert(status + " " + error); },
//column definitions
colNames: ['Id', 'ProductId', 'Reseller Name', 'Link', 'Link Status'],
colModel: [
{ name: 'Id', index: 'Id', width: 40, sortable: false, resizable: true, editable: false, search: false, key: true, editrules: { edithidden: true }, hidden: true },
{ name: 'ProductId', index: 'ProductId', width: 190, sortable: true, sorttype: 'text', resizable: true, editable: true, search: true, stype: 'select', edittype: "select", editoptions: { value: productData }, editrules: { required: true} },
{ name: 'ResellerName', indexme: 'ResellerName', width: 190, sortable: false, sorttype: 'text', resizable: true, editable: true, search: true, stype: 'select', edittype: "select", editoptions: { value: resellerData }, editrules: { required: true }, searchoptions: { sopt: ['eq'], value: resellerSearchData} },
{ name: 'Link', index: 'Link', width: 320, sortable: true, sorttype: 'text', resizable: true, editable: true, search: true, edittype: "textarea", editoptions: { rows: "3", cols: "50" }, editrules: { required: true }, searchoptions: { sopt: ['cn']} },
{ name: 'LinkStatus', index: 'LinkStatus', width: 100, sortable: false, resizable: true, editable: false, search: false, formatter: linkStatusFormatter}],
//grid settings
//rowList: [10, 25, 50],
rowNum: 20,
pager: '#pager2',
sortname: 'ProductId',
sortorder: 'asc',
height: '100%',
viewrecords: true,
gridview: true,
loadonce: true,
viewsortcols: [false, 'vertical', true],
caption: " Product links ",
//grid events
onSelectRow: function (id) {
if (id && id !== lastsel) {
if (lastsel == "newid") {
jQuery('#list2').jqGrid('delRowData', lastsel, true);
}
else {
jQuery('#list2').jqGrid('restoreRow', lastsel);
}
jQuery('#list2').jqGrid('editRow', id, true, null, afterSave); //reload on success
lastsel = id;
}
},
gridComplete: function () {
//$("#list2").setGridParam({ datatype: 'local', page: 1 });
$("#pager2 .ui-pg-selbox").val(25); //changing the selected values triggers paging to work for some reason
}
});
//page settings
jQuery("#list2").jqGrid('navGrid', '#pager2',
{ del: false, refresh: false, search: false, add: false, edit: false }
);
//refresh grid button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Refresh", title: "Refresh grid", buttonicon: 'ui-icon-refresh',
onClickButton: function () {
reload();
}
});
//clear search button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Clear search", title: "Clear Search", buttonicon: 'ui-icon-refresh',
onClickButton: function () {
mygrid[0].clearToolbar();
}
});
//add row button
jQuery("#list2").jqGrid('navButtonAdd', '#pager2', { caption: "New", buttonicon: 'ui-icon-circle-plus',
onClickButton: function (id) {
var datarow = { Id: "newid", ProductId: "", ResellerName: "", Link: "" };
jQuery('#list2').jqGrid('restoreRow', lastsel); //if editing other row, cancel this
lastsel = "newid"; // id;
var su = jQuery("#list2").addRowData(lastsel, datarow, "first");
if (su) {
jQuery('#list2').jqGrid('editRow', lastsel, true, null, afterSave); //reload on success
jQuery("#list2").setSelection(lastsel, true);
}
},
title: "New row"
});
//delete row button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Delete", title: "Delete row", buttonicon: 'ui-icon-circle-minus',
onClickButton: function () {
if (lastsel) {
if (confirm('Are you sure you want to delete this row?')) {
var url = '/public/Gadgets/LinkGadget/Edit/' + currentLang;
var data = { oper: 'del', id: lastsel };
$.post(url, data, function (data, textStatus, XMLHttpRequest) {
reload();
});
lastsel = null;
}
else {
jQuery("#list2").resetSelection();
}
}
else {
alert("No row selected to delete.");
}
}
});
jQuery("#list2").jqGrid('filterToolbar');
}
//Used by initGrid - formats link status column by adding button
function linkStatusFormatter(cellvalue, options, rowObject) {
if (rowObject.Id != "newrow")
return "<input style='height:22px;width:90px;' type='button' " + "value='Check link' " + "onclick=\"CheckLink(this, '" + rowObject.Id + "'); \" />";
else
return "";
}
//Used by initGrid - reloads grid
function reload() {
//jqgrid setting "loadonce: true" will reset datatype from json to local after grid has loaded. "datatype: local"
// does not allow server reloads, therefore datatype is reset before trying to reload grid
$("#list2").setGridParam({ datatype: 'json' }).trigger('reloadGrid');
//mygrid[0].clearToolbar();
lastsel = null;
//Comments: after reload, toolbar filter is not applied to refreshed data. Tried row below without luck
//mygrid[0].triggerToolbar();
}
//after successful save, reload grid and deselect row
function afterSave() {
reload();
}
Your data is not getting re binded to the grid after save/update delete

jqGrid with Virtual Scrolling not returning records in correct order

We're using a jqGrid 3.8.2 with virtual scrolling to scroll a list of records. It works well if the user is scrolling through the list slowly. As soon as the user grabs the scroll bar and quickly scrolls all the way to the bottom the records returned in the grid are completely out of order and sometimes duplicated. The AJAX call we are making to get the records calls a WCF service that returns the records from a database to the AJAX callback in the jqGrid in which the data then gets loaded to the grid. The database expects a page number which in turn indicates which page of records we want.
I am pretty sure the results are coming back in the wrong order due to timing of the AJAX calls. Meaning the calls aren't always first in first out. Newer calls are likely being returned back to the jqGrid before earlier calls.
Any thoughts on how to get this to work correctly? Any steps that I could take to help get us going in the right direction?
If it helps, here is the js configuration:
PersonalListContactGridControl.GetGridConfig = function() {
var jqGridConfig = {
url: Common.AjaxService.serviceUrl + "/GetPersonalListContacts",
datatype: "JSON",
ajaxGridOptions: { contentType: "application/json; charset=utf-8" },
mtype: "POST",
autowidth: true,
height: PersonalListContactGridControl.Constants.Height,
altRows: true,
sortname: "LastName",
viewrecords: true,
emptyrecords: "",
loadtext: '',
multiselect: true,
//sortorder: "desc",
//- virtual scrolling:: 1 ON / 0 OFF
loadonce: false, // SUPPORT FOR REBIND
rowNum: PersonalListContactGridControl.Constants.GridPageSize,
scroll: 1,
gridview: true,
//- column header text
colNames: ['EndPointID',
PersonalListContactGridControl.Constants.FirstNameColumnDisplayText,
PersonalListContactGridControl.Constants.LastNameColumnDisplayText,
PersonalListContactGridControl.Constants.EmailFaxColumnDisplayText,
PersonalListContactGridControl.Constants.TypeColumnDisplayText],
//- column specific definitions
colModel: [
{ name: 'EndPointID', index: 'EndPointID', hidden: true },
{ name: 'FirstName', index: 'FirstName', width: 155, align: 'left', editable: false, title: true,
hidden: false, resizable: true, sortable: true, editoptions: { readonly: true },
formatter: PersonalListContactGridControl.formatLink },
{ name: 'LastName', index: 'LastName', width: 155, align: 'left', editable: false, title: true,
hidden: false, resizable: true, sortable: true, editoptions: { readonly: true },
formatter: PersonalListContactGridControl.formatLink },
{ name: 'EmailAddress', index: 'EmailAddress', width: 240, align: 'left', editable: false, title: true,
hidden: false, resizable: true, sortable: true, editoptions: { readonly: true },
formatter: PersonalListContactGridControl.formatEmailFax },
{ name: 'EndPointType', index: 'EndPointType', width: 60, align: 'left', editable: false, title: true,
hidden: false, resizable: true, sortable: true, editoptions: { readonly: true },
formatter: PersonalListContactGridControl.formatType }
],
//- jqGrid's "reader" ... the structure of the JSON/XML returned (Fiddler) must match this
jsonReader: {
root: "d.Contacts",
total: function(obj) {
return Math.ceil(obj.d.TotalRecords / PersonalListContactGridControl.Constants.GridPageSize);
},
records: function(obj) {
return obj.d.TotalRecords;
},
id: 'EndPointID',
repeatitems: false
},
serializeGridData: function(jqGridParms) {
//alert(jqGridParms.page);
return PersonalListContactGridControl.GetRequest(jqGridParms);
},
loadComplete: function(data) {
if (data.d) {
if (data.d.ResponseProperties.Success === false) {
if (data.d.ResponseProperties.ErrorMessage.indexOf('The List has been deleted') > -1) {
ManagePersonalList.OnPersonalListErrorHandler();
return;
}
}
var grid = PersonalListContactGridControl.Grid();
if (data.d.Contacts == null || data.d.Contacts.length == 0) { // are there any records?
// check if row exists
if (!grid.getInd(-1)) {
if (PersonalListContactGridControl.SearchString == "") {
grid.addRowData(-1, { "FirstName": PersonalListContactGridControl.Constants.NoContactDisplayText });
}
else {
grid.addRowData(-1, { "FirstName": PersonalListContactGridControl.Constants.NoContactForSearchDisplayText });
}
grid.find('#-1 input').hide(); // takeout the selection checkbox
}
PersonalListGridControl.ToggleExportButton(false);
}
else {
if (PersonalListContactGridControl.Constants.dtoToSelectID != null) {
if (PersonalListContactGridControl.SelectContactById(PersonalListContactGridControl.Constants.dtoToSelectID, true))
PersonalListContactGridControl.Constants.dtoToSelectID = null;
}
PersonalListGridControl.ToggleExportButton(true);
}
// cache the return objects
PersonalListContactGridControl.DTOS = PersonalListContactGridControl.DTOS.concat(data.d.Contacts);
PersonalListContactGridControl.InitRows();
}
},
loadError: function(xhr, status, error) {
alert("Type: " + status + "; Response: " + xhr.status + " " + xhr.statusText);
},
onCellSelect: function(rowid, iCol, cellcontent, e) {
if (iCol == 0)
PersonalListContactGridControl.CheckItem();
else
PersonalListContactGridControl.SelectContactById(rowid);
},
onSelectRow: function(id, status) {
if (!status) return;
},
onSelectAll: function() {
var grid = PersonalListContactGridControl.Grid();
var selections = new Array();
selections = grid.getGridParam('selarrrow');
if (selections[0] == -1) {
//if -1, then no rows are available
PersonalListContactGridControl.UpdateHeaderCount(0);
}
else {
PersonalListContactGridControl.UpdateHeaderCount(selections.length);
ManagePersonalList.OnSelectAllChanged(this, { Ids: selections });
}
}
};
return jqGridConfig;
}
Try changing your JSONReader to..
jsonReader: {
root: "d.Contacts",
page: "d.currpage",
total: "d.totalpages",
records: "d.TotalRecords",
id: 'EndPointId',
repeatitems: false
},
the d.totalpages and d.currpage should come back from the AJAX call

Resources