通過Ziege's answer看完後,我想到了發生了什麼事情在那裏。我想出了一個更簡單的方法,在第一個請求發送到服務器之前獲取初始化的默認值。
下面是一個完整的工作示例。這個想法是,有一個列過濾器的狀態下拉,「活躍」和「關閉」,我希望默認爲「活躍」。該代碼有註釋來解釋發生了什麼:
$('#deals').jqGrid({
colNames: ['...','Status','...'],
colModel: [
{ ... },
// Use the defaultValue attribute to set your defaults in the searchOptions object
{ name: 'Status', stype: 'select', searchoptions: { defaultValue: 'Active', value: {"":"All","Active":"Active","Closed":"Closed",}, sopt: [ 'eq'] }, width: 60 },
{ ... }
],
// Here's where we intercept each server request to cancel it if it's the first one.
// Returning false from this method causes the request to the server to be aborted.
beforeRequest: function() {
// Define a local reference to the grid
var $requestGrid = $(this);
// Check a data value for whether we've completed the setup.
// This should only resolve to true once, on the first run.
if ($requestGrid.data('areFiltersDefaulted') !== true) {
// Flip the status so this part never runs again
$requestGrid.data('areFiltersDefaulted', true);
// After a short timeout (after this function returns false!), now
// you can trigger the search
setTimeout(function() { $requestGrid[0].triggerToolbar(); }, 50);
// Abort the first request
return false;
}
// Subsequent runs are always allowed
return true;
},
url: 'Url/to/your/action',
datatype: 'json',
mtype: 'POST',
pager: '#deals-pager',
rowNum: 15,
sortname: 'Status',
sortorder: 'desc',
viewrecords: true,
height: '100%'
}).jqGrid('filterToolbar', { stringResult: true });
這也適用於Lib.Web.Mvc
庫(.NET),它不支持local
數據類型。
如果您有多個網格,或者希望將beforeRequest邏輯移動到共享庫,簡單地將其作爲一個獨立的功能,並在網格設置按名稱引用它:
function jqGridFilterSetupRequestHandler = function() {
var $requestGrid = $(this);
if ($requestGrid.data('areFiltersDefaulted') !== true) {
$requestGrid.data('areFiltersDefaulted', true);
setTimeout(function() { $requestGrid[0].triggerToolbar(); }, 50);
return false;
}
return true;
}
$('#deals').jqGrid({
colNames: ['...','Status','...'],
colModel: [
{ ... },
// Use the defaultValue attribute to set your defaults in the searchOptions object
{ name: 'Status', stype: 'select', searchoptions: { defaultValue: 'Active', value: {"":"All","Active":"Active","Closed":"Closed",}, sopt: [ 'eq'] }, width: 60 },
{ ... }
],
beforeRequest: jqGridFilterSetupRequestHandler,
url: 'Url/to/your/action',
datatype: 'json',
mtype: 'POST',
pager: '#deals-pager',
rowNum: 15,
sortname: 'Status',
sortorder: 'desc',
viewrecords: true,
height: '100%'
}).jqGrid('filterToolbar', { stringResult: true });
馬克,謝謝很好的答案。這也解決了我的問題。 – Justin 2011-03-24 03:14:51
這是我想要做的,但它不工作,除非我在setTimeout中包裝triggerToolbar調用,就像他在原始問題中的做法:( – heisenberg 2012-09-28 19:05:14
@heisenberg非常感謝您的評論,我還需要setTimeout爲此,此解決方案工作得相當不錯 - 在過濾數據呈現時第一次加載時短暫閃爍有點令人不快。 – 2014-07-29 15:16:55