看完Ziege's answer之后,我想到了那里发生的事情。我想出了一个更简单的方法来在第一个请求到达服务器之前初始化默认值。
这是一个完整的工作示例。这个想法是有一个列过滤器,其中包含状态下拉列表,“活动”和“关闭”,我希望默认为“活动”。代码有 cmets 来解释发生了什么:
$('#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 });
这也适用于不支持 local 数据类型的 Lib.Web.Mvc 库 (.NET)。
如果您有多个网格,或者想将 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 });