本系列第六講已提供完整原始碼下載,建議先取得程式碼再閱讀本文。本講將著重於 EasyUI DataGrid 的基礎整合,建立共用的視圖版面模版,並示範 Controller 如何產生符合 DataGrid 規範的 JSON 資料。
在 Views/Shared 下建立 _Index_Layout.cshtml,統一引用 jQuery、EasyUI 核心腳本與樣式:
<!DOCTYPE html>
<html>
<head>
<title>Main</title>
<script src="@Url.Content("~/Scripts/jquery.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.easyui.min.js")" type="text/javascript"></script>
@Styles.Render("~/Content/css")
@Styles.Render("~/Content/themes/blue/css")
</head>
<body>
<div style="padding:5px 5px 0px 5px;">
@RenderBody()
</div>
</body>
</html>
後續所有列表頁面皆繼承此版面,僅需放置一個 <table id="List"></table> 並初始化 DataGrid:
@using App.Admin;
@using App.Common;
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Index_Layout.cshtml";
}
<table id="List"></table>
<script type="text/javascript">
$(function () {
$('#List').datagrid({
url: '/SysSample/GetList',
width: $(window).width() - 10,
method: 'post',
height: $(window).height() - 35,
fitColumns: true,
sortName: 'Id',
sortOrder: 'desc',
idField: 'Id',
striped: true,
singleSelect: true,
rownumbers: true,
columns: [[
{ field: 'Id', title: 'ID', width: 80 },
{ field: 'Name', title: '名稱', width: 120 },
{ field: 'Age', title: '年齡', width: 80, align: 'right' },
{ field: 'Bir', title: '生日', width: 80, align: 'right' },
{ field: 'Photo', title: '照片', width: 250 },
{ field: 'Note', title: '說明', width: 60, align: 'center' },
{ field: 'CreateTime', title: '創建時間', width: 60, align: 'center' }
]]
});
});
</script>
在 SysSampleController 新增 GetList 方法,回傳 DataGrid 所需的 total 與 rows 結構:
[HttpPost]
public JsonResult GetList() {
List<SysSampleModel> list = m_BLL.GetList("");
var json = new {
total = list.Count,
rows = (from r in list
select new SysSampleModel() {
Id = r.Id,
Name = r.Name,
Age = r.Age,
Bir = r.Bir,
Photo = r.Photo,
Note = r.Note,
CreateTime = r.CreateTime
}).ToArray()
};
return Json(json, JsonRequestBehavior.AllowGet);
}
透過版面模版統一資源引用,配合標準化的 JSON 回傳格式,可大幅簡化後續列表頁面的開發工作量。