在 EasyUI DataGrid 中,某列需顯示民族名稱(文字),但編輯時需傳遞民族 ID(數字)。資料庫存儲的是 ID,直接綁定會導致顯示 ID 而非名稱;若後端直接返回名稱,則編輯時無法獲取 ID。Combobox 配置如下:
editor: {
type: 'combobox',
options: {
required: true,
url: '/handler/dict.ashx?flag=tree&t=Nation',
parentField: 'pid',
textFiled: 'text',
valueField: 'id',
method: 'get',
lines: true,
editable: false,
panelHeight: 130,
panelMaxWidth: 200
}
}
後端返回 JSON 範例:[{"id":0,"pid":-1,"text":"請選擇"},{"id":3,"pid":-1,"text":"123"},{"id":2,"pid":-1,"text":"民族1"}]
<script> 標籤載入後端資料,生成全域陣列 arrMZ,避免每次編輯發起 AJAX 請求。
<script src="/handler/dict.ashx?flag=tree&t=Nation"></script>
// 後端需輸出: var arrMZ=[{}...];
editor 的 url 改為 data: arrMZ。
editor: {
type: 'combobox',
options: {
required: true,
parentField: 'pid',
data: arrMZ, // 直接使用本地資料
valueField: 'id',
textField: 'text'
}
}
formatter 函數,根據 value 查找 arrMZ 返回對應文字。
formatter: function(v) {
for (var i = 0; i < arrMZ.length; i++) {
if (arrMZ[i]['id'] == v) return arrMZ[i]['text'];
}
return v;
}