如何在加载时按降序对列进行排序? [英] How do I get a column to be sort in descending order upon loading?

查看:116
本文介绍了如何在加载时按降序对列进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在加载时按降序获得排序的列.我已经在堆栈溢出中看到了一些问题/答案,但这都取决于jqGrid配置.我还没有开始工作...从服务器接收到数据后,必须在本地完成.

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.

谢谢..

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

推荐答案

您使用loadonce: true选项.在这种情况下,服务器(在您的情况下为'../websrvc/JqGrid.ashx')应返回排序的数据.这是jqGrid的要求.我发布到trirand

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 with loadonce: true option.

因此,要获得最佳结果,您的ASHX代码应获取sidxsord参数(context.Request["sidx"]context.Request["sord"]),并返回所有按sidx排序的网格排序的行到sord方向.

So to have the best results your ASHX code should get sidx and sord parameters (context.Request["sidx"], context.Request["sord"]) and returns all rows of grid sorted by sidx corresponds to sord direction.

只有在服务器端确实有实现方面的问题时,才可以在客户端执行此操作.首先,应将sortname: 'StockDate'sortorder: 'desc'设置为与要具有的排序结果相对应的值.如果需要按Year列对网格进行排序,则应使用sortname: 'Year'.然后,您应该在第一次加载后立即重新加载网格一次.您可以使用以下loadComplete

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' and sortorder: 'desc' to values which corresponds to sorting results which you want to have. If you need to sort grid by Year column then you should use sortname: 'Year'. Then you should reload the grid once directly after the first loading. You can do this with the following 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: trueloadComplete内部重新加载网格时工作迅速.

UPDATE: Free jqGrid fork of jqGrid, which I develop since the end of 2014, has the option forceClientSorting: true, which can be combined with loadonce: 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 option forceClientSorting: true replaces all the code described in the answer. On cause forceClientSorting: true works much quickly as reloading of grid inside of loadComplete.

这篇关于如何在加载时按降序对列进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆