I'm wondering how do I get a sorted column in descending order upon loading. I have seen some questions/answers in stack-overflow but it all depends on the jqGrid configuration. That I haven't got it to work... It need to be done locally once the data is received from the server.
Thanks..
<link rel="stylesheet" type="text/css" href="../css/jquery-ui-v1.10.3.themes/base/minified/jquery-ui.min.css" />
<link rel="stylesheet" type="text/css" href="../css/jqgrid-v4.5.0/ui.multiselect.css" />
<link rel="stylesheet" type="text/css" href="../css/jqgrid-v4.5.0/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" href="../css/jqgrid-v4.5.0/ui.jqgrid-bio-override.css" />
<script src="../scripts/jquery-ui-v1.10.3/minified/jquery-ui.min.js" type="text/javascript"></script>
<script src="../scripts/jqgrid-v4.5.0/ui.multiselect.js" type="text/javascript"></script>
<script src="../scripts/jqgrid-v4.5.0/i18n/grid.locale-en.js" type="text/javascript"></script>
<!--<script src="../scripts/jqgrid-v4.5.0/jquery.jqGrid.min.js" type="text/javascript"></script>-->
<script src="../scripts/jqgrid-v4.5.0/jquery.jqGrid.src.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
<% var httpPrefix = (EnvironmentSetting.WebServerEnvironment_DeveloperMachine == true ? "http" : "https"); %>
<% var urlRandom = new System.Random(5); %>
<% var httpAdditionalDetailToken = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + urlRandom.Next(1000).ToString(); %>
<% var postQuickQuoteSalePrice = (String.IsNullOrEmpty(Request["QuickQuoteSalePrice"]) == true ? "" : Convert.ToString(Request["QuickQuoteSalePrice"])); %>
//My Inventory Spreadsheet...
var jqgridSpreadsheetId = 'MyInventoryJqgrid_Spreadsheet';
var jqgridPagerId = 'MyInventoryJqgrid_Pager';
var jqgridGroupColumnHeader = 'MyInventoryJqgrid_GroupColumnHeader';
var jqgridDialogLinkOptions = 'MyInventoryJqgrid_PopupDialogLinkOptions';
var jqgridColumnIdStockNumber = 1;
var jqgridColumnIdVin = 2;
var jqgridColumnIdInventoryTrackerLocationId = 13;
var jqgridColumnNameLinks = "Links";
var jqgridHiddenDialog1 = "";
//My Inventory Summary Spreadsheet...
var jqgridSummarySpreadsheetId = 'MyInventorySummaryJqgrid_Spreadsheet';
//var jqgridData = '{"total":3,"page":1,"records":3,"rows":[{"id":1,"cell":["73157978","1234","1GTCS149698119451","2009","GMC","Canyon Regular Cab","SLE Pickup 2D 6 ft","34555","4500.00","2013-04-30","0.00","4500.00","14",""]},{"id":2,"cell":["72174115","","1G1JE6SH0C4134329","2012","Chevrolet","Sonic","LTZ Hatchback Sedan 4D","0","100.00","2013-01-14","0.00","100.00","120",""]},{"id":3,"cell":["72167761","Rrrrr","1GNEK13TX1R173136","2001","Chevrolet","Tahoe","Sport Utility 4D","5000","6000.00","2013-01-11","0.00","6000.00","123","San Francisco"]}]}';
//=====================================================================================================================================================================================================
//=====================================================================================================================================================================================================
//My Inventory Spreadsheet...
//=====================================================================================================================================================================================================
//=====================================================================================================================================================================================================
//jqGrid Plugin...
//http://www.trirand.com...
//http://www.codeproject.com/Articles/201883/jqGrid-Quick-Tips... //Useful quick-tip to get up and going fast...
$('#'+jqgridSpreadsheetId).jqGrid({
url: '../websrvc/JqGrid.ashx',
datatype: 'json',
mtype: 'POST',
postData: { WhichJqgridTemplate: '<%=JqqridTools.Template.MyInventory%>', WhichAction: '<%=JqqridTools.Action.Display%>', WebpageQuickQuoteSalePrice: '<%=postQuickQuoteSalePrice%>' },
colNames: ['Id', 'Stock Number', 'VIN', 'Year', 'Make', 'Model', 'Trim', 'Mileage', 'Purchase Price', 'Stock Date', 'Repair Cost', 'Total Cost', 'Days In Inventory', 'Hidden-Inventory-Tracker-Location-Id', 'Inventory Tracker Location', 'Links'], //Display Text in Column Header...
colModel: [
{ name: 'Id', index: 'Id', sorttype: 'int', width: 0, align: 'left', hidden: true, hidedlg: true }, //"hidedlg" is use to hide the hidden column in "Column Chooser"...
{ name: 'StockNumber', index: 'StockNumber', sorttype: 'text', width: 100, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Vin', index: 'Vin', sorttype: 'text', width: 140, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Year', index: 'Year', sorttype: 'int', width: 50, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Make', index: 'Make', sorttype: 'text', width: 80, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Model', index: 'Model', sorttype: 'text', width: 80, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Trim', index: 'Trim', sorttype: 'text', width: 100, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Mileage', index: 'Mileage', sorttype: 'int', width: 60, align: 'center', formatter: 'number', formatoptions: {decimalSeparator:'',thousandsSeparator:',',decimalPlaces:0,defaultValue:'0'} },
{ name: 'PurchasePrice', index: 'PurchasePrice', sorttype: 'currency', width: 80, align: 'center', formatter: 'currency', formatoptions: {decimalSeparator:'.',thousandsSeparator:',',decimalPlaces:2,defaultValue:'0.00',prefix:'$',suffix:''} },
{ name: 'StockDate', index: 'StockDate', sorttype: 'date', width: 80, align: 'center', formatter: 'date', formatoptions: { newformat: 'm/d/Y' } }, //"formatter" and "formatoptions" is required for date sorting to works properly...
{ name: 'RepairCost', index: 'RepairCost', sorttype: 'currency', width: 80, align: 'center', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '0.00', prefix: '$', suffix: '' } },
{ name: 'TotalCost', index: 'TotalCost', sorttype: 'currency', width: 80, align: 'center', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '0.00', prefix: '$', suffix: '' } },
{ name: 'DaysInInventory', index: 'DaysInInventory', sorttype: 'int', width: 65, align: 'center', formatter: 'number', formatoptions: { decimalSeparator: '', thousandsSeparator: ',', decimalPlaces: 0, defaultValue: '1' } },
{ name: 'InventoryTrackerLocationId', index: 'InventoryTrackerLocationId', sorttype: 'int', width: 0, align: 'left', hidden: true, hidedlg: true }, //"hidedlg" is use to hide the hidden column in "Column Chooser"...
{ name: 'InventoryTrackerLocation', index: 'InventoryTrackerLocation', sorttype: 'text', width: 120, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
//Links is not present in json data from the website, so we customize it here...
{ name: 'Links', index: 'Links', sorttype: 'text', width: 80, align: 'center', formatter: function (cellValue, options, rowObject) { return "<span style='text-decoration:underline;cursor:pointer;'>Links</span>" }, search: false } //"search" is use to hide the field in search dialog...
],
beforeSelectRow: function (rowid, e) {
if (this.p.colModel[$.jgrid.getCellIndex($(e.target).closest("td")[0])].name === jqgridColumnNameLinks) {
jqgridPopupDialogLinkOptions(
$('#' + jqgridSpreadsheetId).getCell(rowid, jqgridColumnIdStockNumber),
$('#' + jqgridSpreadsheetId).getCell(rowid, jqgridColumnIdVin),
$('#' + jqgridSpreadsheetId).getCell(rowid, jqgridColumnIdInventoryTrackerLocationId)
);
return false;
}
},
pager: '#'+jqgridPagerId,
rowNum: 10,
rowList: [5, 10, 20, 50], //Drop-down selection in footer - To show how many rows per page...
//This "sortname"/"sortorder" must be specified for "getGridParam"'s 'datatype'/'sortname'/'sortorder' (column sorting) to work. (Some kind of jqGrid bug or feature which we need to hack to do a workaround with)...
<% if(postQuickQuoteSalePrice.Length > 0) { %>
sortname: 'TotalCost', sortorder: 'desc', //Coming from Quick-Quote webpage...
<% }else{ %>
sortname: 'StockDate', sortorder: 'desc', //Coming from any webpages...
<% } %>
viewrecords: true,
//gridview: true,
imgpath: '',
caption: 'My Inventory',
width: 1022,
shrinkToFit: false,
height: 400,
sortable: true, /* This allows both 1) Moving columns sideway to other location fields and 2) for jqGrid Column Chooser Plugin / JQuery Multiselect Plugin to work... */
grouping: true, /* This allows row data to be group into row grouping... */
loadonce: true, //In this case, use "sorttype" property in "colModel" for it to work when "loadonce" is set to true...
emptyrecords: "No records to display",
loadError: function (xhr, st, err) {
alert("An error had occurred, please try again or notify webmaster of this error");
},
loadComplete: function () {
var $self = $(this); //This is needed to seperate itself from binding jqGrid or $(this) objects for it to work. It wouldn't work without it...
if ($(this).jqGrid('getGridParam', 'datatype') === 'json') { //This the value when loading webpage then the value of "datatype" option will become "local" afterward...
setTimeout(function () {
$self.triggerHandler("reloadGrid");
}, 50);
}
//jqgridSummarySpreadsheetDisplay();
}
});
//jqGrid - My-Inventory-Summary...
function jqgridSummarySpreadsheetDisplay() {
$('#' + jqgridSummarySpreadsheetId).setCell(1, 'TotalVehicles', ($('#' + jqgridSpreadsheetId).getGridParam('records')), {'vertical-align':'middle'}, '', ''); //getGridParam('data').length)
$('#' + jqgridSummarySpreadsheetId).setCell(1, 'TotalPurchaseCost', ($('#' + jqgridSpreadsheetId).getCol('PurchasePrice', false, 'sum')), { 'vertical-align': 'middle' }, '', '');
$('#' + jqgridSummarySpreadsheetId).setCell(1, 'TotalRepairCost', ($('#' + jqgridSpreadsheetId).getCol('RepairCost', false, 'sum')), { 'vertical-align': 'middle' }, '', '');
$('#' + jqgridSummarySpreadsheetId).setCell(1, 'TotalCost', ($('#' + jqgridSpreadsheetId).getCol('TotalCost', false, 'sum')), { 'vertical-align': 'middle' }, '', '');
}
//Navigation Buttons...
//http://www.trirand.com/jqgridwiki/doku.php?id=wiki:navigator...
//http://www.trirand.com/jqgridwiki/doku.php?id=wiki:custom_buttons...
//This is required for "navButtonAdd" to appear...
$('#'+jqgridSpreadsheetId).navGrid('#'+jqgridPagerId,
{ edit: false, add: false, del: false, search: true, view: false, refresh: false }, //Options...
{}, //{edit}...
{}, //{add}...
{}, //{del}...
{
multipleSearch: true, multipleGroup: false, closeOnEscape: true, closeAfterSearch: true, searchOnEnter: true, showQuery: false, width: 550, caption: "Search Records",
//overlay: 1, //If overlay is set to 0, grid is disabled but if set to 1, grid is active and you can play with both search and grid at once.
afterRedraw: function () {
//Notice: May sure the "rule" drop-down selection is set to "all" by default...
$("input.add-rule", this).button().val("Add Rule");
$("input.delete-rule", this).button().val("Remove Rule");
$("select.opsel", this).hide();
}
}, //{search}...
{} //{view}...
);
//$('#'+jqgridSpreadsheetId).navSeparatorAdd('#'+jqgridPagerId, { sepclass: 'ui-separator', sepcontent: '' }); //Seperator bar icon...
$('#'+jqgridSpreadsheetId).navButtonAdd('#'+jqgridPagerId, {
position: "first",
caption: "",
buttonicon: "ui-icon-calculator",
title: "Show Columns",
//cursor: "pointer", //This does not work...
onClickButton: function () {
//http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jquery_ui_methods&s[]=column&s[]=chooser...
$(this).columnChooser({
title: "Show Columns",
width: 600,
done: function (perm) {
if (perm) { //"OK" button are clicked...
this.jqGrid("remapColumns", perm, true);
//} else { //"Cancel" button or "x" button are clicked...
}
}
});
}
});
//Columns Header Grouping...
//[Drag a column]...
$('tr.ui-jqgrid-labels th div').draggable({
appendTo: 'body',
helper: 'clone'
});
//[Drop a column]...
$('#'+jqgridGroupColumnHeader+' ol').droppable({
activeClass: 'ui-state-default',
hoverClass: 'ui-state-hover',
accept: ':not(.ui-sortable-helper)',
drop: function (event, ui) {
var $this = $(this);
$this.find('.placeholder').remove();
var groupingColumn = $('<li></li>').attr('data-column', ui.draggable.attr('id').replace('jqgh_' + jqgridSpreadsheetId + '_', ''));
$('<span class="ui-icon ui-icon-close"></span>').click(function () {
$(this).parent().remove();
$('#' + jqgridSpreadsheetId).jqGrid('groupingRemove');
$('#'+jqgridSpreadsheetId).jqGrid('groupingGroupBy', $('#'+jqgridGroupColumnHeader+' ol li:not(.placeholder)').map(function () { return $(this).attr('data-column'); }).get());
//Make the text re-appear after the very last column is removed...
if ($('#'+jqgridGroupColumnHeader+' ol li:not(.placeholder)').length === 0) {
$('<li class="placeholder">Drop header columns here</li>').appendTo($this);
}
}).appendTo(groupingColumn);
groupingColumn.append(ui.draggable.text());
groupingColumn.appendTo($this);
$('#'+jqgridSpreadsheetId).jqGrid('groupingRemove');
$('#'+jqgridSpreadsheetId).jqGrid('groupingGroupBy', $('#'+jqgridGroupColumnHeader+' ol li:not(.placeholder)').map(function () { return $(this).attr('data-column'); }).get());
}
});
//[Re-arrange columns' position in "Group Column Header" box]...
$('#' + jqgridGroupColumnHeader + ' ol').sortable({
items: 'li:not(.placeholder)',
sort: function () {
$(this).removeClass('ui-state-default');
},
stop: function () {
$('#'+jqgridSpreadsheetId).jqGrid('groupingRemove');
$('#'+jqgridSpreadsheetId).jqGrid('groupingGroupBy', $('#'+jqgridGroupColumnHeader+' ol li:not(.placeholder)').map(function () { return $(this).attr('data-column'); }).get());
}
, revert: true
});
//Reposition the GUI stuff on browser resizing...
$(window).resize(function () {
$('#' + jqgridDialogLinkOptions).dialog("option", "position", "center");
});
//=====================================================================================================================================================================================================
//=====================================================================================================================================================================================================
//=====================================================================================================================================================================================================
//=====================================================================================================================================================================================================
//My Inventory Summary...
//=====================================================================================================================================================================================================
//=====================================================================================================================================================================================================
//jqGrid Plugin...
$('#' + jqgridSummarySpreadsheetId).jqGrid({
datatype: 'jsonstring', //'local',
datastr: [{ "id": 1, "cell": ["", "", "", ""] }], //It is surprising that it accepted blank values...
colNames: ['Total Vehicles', 'Total Purchase Cost', 'Total Repair Cost', 'Total Cost'], //Display Text in Column Header...
colModel: [
//In this case, use "sorttype" property in "colModel" for it to work when "loadonce" is set to true...
{ name: 'TotalVehicles', index: 'TotalVehicles', sorttype: 'int', align: 'center', sortable: false, formatter: 'number', formatoptions: { decimalSeparator: '', thousandsSeparator: ',', decimalPlaces: 0, defaultValue: '' } },
{ name: 'TotalPurchaseCost', index: 'TotalPurchaseCost', sorttype: 'currency', align: 'center', sortable: false, formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '', prefix: '$', suffix: '' } },
{ name: 'TotalRepairCost', index: 'TotalRepairCost', sorttype: 'currency', align: 'center', sortable: false, formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '', prefix: '$', suffix: '' } },
{ name: 'TotalCost', index: 'TotalCost', sorttype: 'currency', align: 'center', sortable: false, formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '', prefix: '$', suffix: '' } }
],
caption: 'My Inventory Summary',
width: 1022,
shrinkToFit: true,
height: '100%',
loadonce: false, //In this case, use "sorttype" property in "colModel" for it to work when "loadonce" is set to true...
emptyrecords: "No records to display",
loadError: function (xhr, st, err) {
alert("An error had occurred, please try again or notify webmaster of this error");
}
});
//=====================================================================================================================================================================================================
//=====================================================================================================================================================================================================
});
</script>
<div id="divWebLayout2" style="padding-top:2px;padding-bottom:20px;">
<div id="MyInventoryJqgrid_GroupColumnHeader">
<div class="ui-widget-content"><ol><li class="placeholder">Drop header columns here</li></ol></div>
<div>
<table id="MyInventoryJqgrid_Spreadsheet"></table>
<div id="MyInventoryJqgrid_Pager" style="text-align:center;"></div>
</div>
</div>
</div>
<div id="divWebLayout3" style="padding-bottom:20px;">
<table id="MyInventorySummaryJqgrid_Spreadsheet"></table>
</div>
You use
loadonce: true
option. In the case the server ('../websrvc/JqGrid.ashx'
in your case) should returns sorted data. It's the requirement of jqGrid. I posted to trirand the suggestion to change the behavior, but jqGrid still don't made any changes about sorting of the data loaded withloadonce: true
option.So to have the best results your ASHX code should get
sidx
andsord
parameters (context.Request["sidx"]
,context.Request["sord"]
) and returns all rows of grid sorted bysidx
corresponds tosord
direction.Only if you really have some implementation problem to make sorting on the server side you can do this on the client side. First of all you should set
sortname: 'StockDate'
andsortorder: 'desc'
to values which corresponds to sorting results which you want to have. If you need to sort grid byYear
column then you should usesortname: 'Year'
. Then you should reload the grid once directly after the first loading. You can do this with the followingloadComplete
UPDATE: Free jqGrid fork of jqGrid, which I develop since the end of 2014, has the option
forceClientSorting: true
, which can be combined withloadonce: true
. The option force that sorting and filtering on the client side will be done on the first loading from the server. In other words, the optionforceClientSorting: true
replaces all the code described in the answer. On causeforceClientSorting: true
works much quickly as reloading of grid inside ofloadComplete
.Just setting sortname and sortorder doesn't work. You need the setTimeout as well. This has a drawback: scrolling wont work as it keeps rebuilding the grid it seems. So you jump right on top of the grid again.
Fairly straightforward, set the properties of the grid: Ex: