Как получить сортировку столбца в порядке убывания при загрузке?

Мне интересно, как получить отсортированный столбец в порядке убывания при загрузке. Я видел некоторые вопросы / ответы в переполнении стека, но все это зависит от конфигурации jqGrid. Что у меня нетЭто заставило его работать ... Это нужно сделать локально после получения данных с сервера.

Спасибо..


 
  







    $(document).ready(function () {
        
        
        
        

        //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: '', WhichAction: '', WebpageQuickQuoteSalePrice: '' },
            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)...
             0) { %>
            sortname: 'TotalCost', sortorder: 'desc',  //Coming from Quick-Quote webpage...
            
            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 = $('').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) {
                        $('Drop header columns here').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");
            }
        });
        //=====================================================================================================================================================================================================
        //=====================================================================================================================================================================================================
    });
 


    
         Drop header columns here
         
             
             
         
     
 
 
    
 

Ответы на вопрос(3)

Просто установка sortname и sortorder не делаетт работа. Вам также нужен setTimeout. У этого есть недостаток: прокрутка не будет работать, поскольку она продолжает перестраивать сетку, как кажется. Таким образом, вы прыгаете прямо на вершине сетки снова.

Решение Вопроса

Ты используешьloadonce: true вариант. В случае сервера ('../websrvc/JqGrid.ashx' в вашем случае) должен вернутьотсортированный данные. Это's требование jqGrid. Я отправил в trirandпредложение изменить поведение, но jqGrid по-прежнему неВнесены какие-либо изменения в сортировку данных, загруженных сloadonce: true вариант.

Таким образом, чтобы получить лучшие результаты, ваш код ASHX должен получитьsidx а такжеsord параметры (,context.Request["sidx"]context.Request["sord"]) и возвращает все строки сеткиотсортированный отsidx соответствуетsord направление.

Только если у вас действительно есть проблемы с реализацией для сортировки на стороне сервера, вы можете сделать это на стороне клиента. Прежде всего вы должны установитьsortname: 'StockDate' а такжеsortorder: 'desc' значениям, которые соответствуют результатам сортировки, которые вы хотите получить. Если вам нужно отсортировать сетку поYear столбец, то вы должны использоватьsortname: 'Year', Затем вы должны перезагрузить сетку сразу после первой загрузки. Вы можете сделать это с помощью следующегоloadComplete

loadComplete: function () {
    var $self = $(this);
    if ($self.jqGrid("getGridParam", "datatype") === "json") {
        // the code will be executed only at the first loading because jqGrid
        // changes datatype to "local" after the first loading if we use
        // loadonce option. We use setTimeout to allows jqGrid to make the first
        // loading till the end and reload it AFTER that
        setTimeout(function () {
            $self.triggerHandler("reloadGrid");
        }, 50);
    }
}

ОБНОВИТЬ: Бесплатная jqGrid форк jqGrid, который я разрабатываю с конца 2014 года, имеет опциюforceClientSorting: true, который может быть объединен сloadonce: true, Опция принудительной сортировки и фильтрациина стороне клиента будет сделано при первой загрузке с сервера. Другими словами, вариантforceClientSorting: true заменяет весь код, описанный в ответе. По причинеforceClientSorting: true работает очень быстро, как перезагрузка сетки внутри.loadComplete

Довольно просто, установите свойства сетки: Пример:

        sortname: 'ColumnNameToSortOn',
        sortorder: "desc",

Ваш ответ на вопрос