最近逛了逛 jQuery 資料又發現了一個新的 UI 可以使用,就是 jQuery EasyUI,沒注意到是甚麼時候出現的,之前印象只有jquery ui跟jquery tools,看了一下他的文件內容跟Demo資料,其實也提供蠻多好用的plugin,其中覺得他的datagrid感覺還不錯,順手寫了一個範例記錄一下。
jQuery EasyUi 網址: http://www.jeasyui.com
jQuery EasyUi 中文文件: http://www.phptogether.com/juidoc
範例
Step 1
首先要去 jQuery EasyUi 網站下載檔案,最新版本為 jQuery EasyUI 1.2.5
Step 2
建立新網站,加入jquery及easyui套件
Step 3
建立一頁新aspx網頁及ashx泛型處理常式用來處理ajax需求,將js檔案載入aspx頁面,依序是css, jquery.js, easyui.js
- jquery.easyui.min.js為包含所有plugin,當然也可以單獨載入要使用的plugin檔案,
- 如果需要使用繁體語系,可以在所有.js檔最後面載入 locale 資料夾內的 easyui-lang-zh_TW.js 檔案。
- 因官網下載的datagrid有如果在page中將datagrid放在form標籤中,選擇跳頁會post的問題,所以這邊需要重新載入原作者提供給我的修正檔pagination plugin。
Step 4
依照官網範例其實就可以很簡單的建立起基本雛型,這邊也一樣實際做一下,針對DataGrid easyui是使用<table>標籤,所以在body內加入一個table並且設定一下表頭欄位,表頭欄位也可以在 script 內的 columns properties設定 ,dgl 的 div 是為了使用 Dialog 來做新增資料的介面。
Step 5
接下來就開始撰寫 Java Script 碼,基本用法如下:
1
$('#grid').datagrid({
2
url:'CRUDHandler.ashx', //處理資料面程式
3
columns:[[ //設定欄位
4
{field:'id',title:'ID',width:100},
5
{field:'name',title:'Name',width:100},
6
{field:'age',title:'Age',width:100,align:'right'},
7
{field:'address',title:'Address',width:100}
8
]]
9
});
這使用尚有很多種屬性可以設定,這些屬性在官方文檔內都可以找的到,在這邊我輸入的Script如下:
01
$(function () {
02
var qParams = { id: $("#txtid").val(), name: $("#txtname").val() }; //取得查詢參數
03
var oldRowIndex;
04
var opt = $('#grid');
05
opt.datagrid({
06
width: "auto", //自動寬度
07
height: 320, //固定高度
08
nowrap: false, //不截斷內文
09
striped: true, //列背景切換
10
fitColumns: true, //自動適應欄寬
11
singleSelect: true, //單選列
12
queryParams: qParams, //參數
13
url: 'CRUDHandler.ashx', //資料處理頁
14
idField: 'id', //主索引
15
frozenColumns: [[{ field: 'ck', checkbox: true}]], //顯示核取方塊
16
pageList: [10, 15, 20], //每頁顯示筆數清單
17
pagination: true, //是否啟用分頁
18
rownumbers: true, //是否顯示列數
19
toolbar: [{
20
id: 'btnAdd',
21
text: '新增',
22
iconCls: 'icon-add',
23
handler: function () {
24
insertRow($(this));
25
}
26
}],
27
onClickRow: function (rowIndex) {
28
if (oldRowIndex == rowIndex) {
29
opt.datagrid('clearSelections', oldRowIndex);
30
}
31
var selectRow = opt.datagrid('getSelected');
32
oldRowIndex = opt.datagrid('getRowIndex', selectRow);
33
}
34
}).datagrid("getPager").pagination({
35
buttons: [{
36
id: 'btnEdit',
37
iconCls: 'icon-edit',
38
text: '編輯',
39
handler: function () {
40
editRow();
41
}
42
}, '-', {
43
id: 'btnDel',
44
text: '刪除',
45
iconCls: 'icon-remove',
46
handler: function () {
47
removeRow();
48
}
49
}],
50
onBeforeRefresh: function () {
51
return true;
52
}
53
});
54
$("#btnQry").click(function(){
55
Query();
56
});
57
});
以上這段為主體的Script,這個DataGrid可以處理 查詢、新增、更新、刪除,傳輸資料的格式主要為JSON,接下來必須將對應的方法都補上,開啟新增畫面方法:
1
//開啟新增並位移
2
function insertRow(opt) {
3
var offset = opt.offset();
4
$('#dlg').dialog('open').dialog('setTitle', '新增資料').dialog('move', {
5
left: offset.left,
6
top: offset.top
7
});
8
}
儲存資料方法:
01
//儲存資料
02
function saveData() {
03
if ($(".easyui-validatebox").val() != "") {
04
$.post('CRUDHandler.ashx', 'mode=INS&' + $('#frmAjax input').serialize(), function (result) {
05
if (result.success) {
06
$('#dlg').dialog('close');
07
$.messager.alert('Success', '新增成功!', 'info', function () {
08
$('#grid').datagrid('reload'); // reload
09
});
10
} else {
11
$.messager.alert('Error', result.msg, 'warning'); //錯誤訊息
12
}
13
}, 'json');
14
}
15
else
16
$.messager.alert('警告', '未輸入ID!', 'warning'); //錯誤訊息
17
}
編輯資料列方法(這邊使用直接跳頁至Detail頁面處理:
1
//編輯資料列
2
function editRow() {
3
var row = $("#grid").datagrid('getSelected');
4
if (row != null)
5
window.location.href = "Detail.aspx?mode=UPD&pk=" + row.id;
6
else
7
$.messager.alert('訊息', '尚未選擇需編輯的資料列!', 'info'); //
8
}
刪除資料列方法:
01
//刪除資料列
02
function removeRow() {
03
var row = $("#grid").datagrid('getSelected');
04
if (row) {
05
$.messager.confirm('Confirm', '確定要刪除此筆資料?', function (r) {
06
if (r) {
07
var index = $("#grid").datagrid('getRowIndex', row);
08
//$('#grid').datagrid('deleteRow', index); //取得index
09
$.post('CRUDHandler.ashx', { 'mode': 'DEL', id: row.id }, function (result) {
10
if (result.success) {
11
$.messager.alert('Success', '刪除成功!', 'info', function () {
12
$('#grid').datagrid('reload'); //刷新畫面
13
});
14
} else {
15
$.messager.alert('Error', result.msg, 'warning'); //錯誤訊息
16
}
17
}, 'json');
18
}
19
});
20
21
}
22
else
23
$.messager.alert('訊息', '尚未選擇需刪除的資料列!', 'info'); //
24
}
查詢方法:
01
function Query() {
02
var qid, qname;
03
if ($("#txtid").val() != "")
04
qid = $("#txtid").val();
05
else
06
qid = "";
07
if ($("#txtname").val() != "")
08
qname = $("#txtname").val();
09
else
10
qname = "";
11
12
qParams = { id: qid, name: qname };
13
$('#grid').datagrid('options').queryParams = qParams;
14
$('#grid').datagrid('options').pageNumber = 1;
15
var p = $('#grid').datagrid('getPager');
16
if (p) {
17
$(p).pagination({ pageNumber: 1 });
18
}
19
$("#grid").datagrid('reload');
20
return false;
21
}
以上aspx頁面的Script就差不多完成了,接下來就要處理資料面的問題,我使用了 CRUDHandler.ashx 這隻泛型處理常式來處理Server端的動作,在ashx開始我會先判斷要處理哪種作業,並且執行哪個method。
01
public void ProcessRequest (HttpContext context) {
02
if (context.Request["mode"] != null)
03
{
04
string mode = context.Request["mode"].ToString();
05
switch(mode)
06
{
07
case "Qry":
08
QueryData(context);
09
break;
10
case "INS":
11
InsertData(context);
12
break;
13
case "DEL":
14
DeleteData(context);
15
break;
16
}
17
}
18
}
在查詢的部分我使用SQL資料分頁的方式取得資料並回傳Client端,DataGrid 預設會POST兩個參數回Server端。
- page: 目前頁數
- rows: 顯示的筆數
在Server端必須接收這兩個參數後再去資料庫取得分頁資料,如果需要增加額外的參數就如同我上面的Script碼寫法增加,一個查詢的程式碼大概如下:
01
//查詢資料
02
public void QueryData(HttpContext context)
03
{
04
//資料庫分頁取得資料方法
05
string page = context.Request["page"];
06
string rows = context.Request["rows"];
07
List<users> li = new List<users>();
08
DataSet ds = GetData(int.Parse(rows), int.Parse(page), context);
09
foreach (DataRow dr in ds.Tables[0].Rows)
10
{
11
li.Add(new users()
12
{
13
id = dr["id"].ToString(),
14
name = dr["name"].ToString(),
15
age = dr["age"].ToString(),
16
address = dr["address"].ToString()
17
});
18
}
19
ReturnDate rd = new ReturnDate();
20
rd.total = ds.Tables[1].Rows[0]["TotalCount"].ToString();
21
rd.rows = li;
22
DataContractJsonSerializer json = new DataContractJsonSerializer(rd.GetType());
23
json.WriteObject(context.Response.OutputStream, rd);
24
}
25
26
public class ReturnDate
27
{
28
public string total { get; set; }
29
public List<users> rows { get; set; }
30
}
31
32
public class users
33
{
34
public string id { get; set; }
35
public string name { get; set; }
36
public string age { get; set; }
37
public string address { get; set; }
38
}</users></users></users>
這是我的寫法,將撈出來的資料轉成JSON後在傳到Client,而其他的處理方法就可以依照你自己需求而去撰寫,我這邊就不多撰寫了,這樣就完成了一個DataGrid,實際完成的畫面如下。
範例程式碼