2013-05-19 95 views
0

我想知道如何在加載時以降序獲得排序的列。我在堆棧溢出中看到了一些問題/答案,但這一切都取決於jqGrid配置。我沒有得到它的工作......一旦從服務器收到數據,它就需要在本地完成。如何在加載時按降序對列進行排序?

謝謝..

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

回答

2

您使用loadonce: true選項。在這種情況下,服務器('../websrvc/JqGrid.ashx'在你的情況下)應該返回排序的數據。這是jqGrid的要求。我發佈了更改此行爲的更改the suggestion,但jqGrid仍未對使用loadonce: true選項加載的數據進行排序進行任何更改。

所以讓你的ASHX代碼應該得到sidxsord參數(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); 
    } 
} 

UPDATE做到這一點:Free jqGrid叉jqGrid的,自2014年底,我發展,有選擇forceClientSorting: true,可與loadonce: true結合。在客戶端上進行排序和過濾的選項強制將在第一次從服務器加載時完成。換句話說,選項forceClientSorting: true取代了答案中描述的所有代碼。原因forceClientSorting: true作爲loadComplete內部的重新加載網格很快。

+0

非常有趣。所以這是jqGrid的內置功能,它使這個沒用,直到我們實施一個解決方法,它才能工作。 (本地排序)。感謝您的回答和幫助。它現在工作,我更新了上面的腳本。 – fletchsod

+0

我看到了你提供的「建議」鏈接,它似乎已經從那裏離開了。 :-(我想最終會發生在jqGrid的後續版本中,在GitHub中是否有一個bug報告可供我跟蹤? – fletchsod

+0

你對服務器端的實現問題有所瞭解,這就是爲什麼我在客戶端進行。在網頁上沒有sql查詢,出於某些原因,這些都在存儲庫dll文件中,並且儘可能減少sql注入攻擊。此外,技術正在朝向對象關係映射器[ORM](或數據庫對象)發展。另一個問題是,當我涉及到100萬行時,我無法對數據進行排序,也沒有在MS-SQL中的ORDER-BY中編寫IF-CASE-ELSE語句。它使我們處於MSSQL服務器的擺佈之中,加上Web /數據/服務器模型和技術演進的分離。 – fletchsod

0

相當簡單,設置網格的屬性: 例:

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

我試過那個w /沒有運氣。另外,我需要能夠設置它來自幾個不同的網頁,其中sortname和sortorder都是不同的。 – fletchsod

+0

我們正在使用jqGrid版本4.5.0。我們不在服務器端使用排序,而是在加載時在客戶端進行排序。 – fletchsod

0

只是設置sortname和sortorder不起作用。 您還需要setTimeout。 這有一個缺點:滾動不會工作,因爲它似乎不斷重建網格。 所以你再次跳到電網頂端。