在WEB前端開發中,用到比較多的Grid插件,主要有FlexiGrid和JqGrid兩大插件。這里,我想介紹一下FlexiGrid.
首先我想介紹一下的是FlexiGrid的原理理論的知識。
從FlexiGrid官方文檔來看,他主要能夠將JSON和XML格式的數據轉換成Grid的能力,這里我們主要講解JSON方式。
FlexiGrid對於JSON格式,是有自身的一個格式規范的。一般是這樣:
{page:1,total:2,rows:[{Id:'c0509d34-e860-4698-91e5-210fab32dc2f',cell:['c0509d34-e860-4698-91e5-210fab32dc2f','True','4','31@qq.com']}
,{Id:'c0509d34-e860-4698-91e5-210fab32dc3f',cell:['c0509d34-e860-4698-91e5-210fab32dc3f','False','4','32@qq.com']}]}
從格式上來看,我們傳輸的JSON主要有三個值,page,total,rows.其中page表示當前返回的頁碼,total表示數據的總條數,rows里面嵌套的是行對象。
我們對於JSON的組裝也主要是體現在rows這個節點上,rows可以包括眾多的子對象,每個子對象為Table中的一行,或者理解為數據中的某一個實體。
每一個Rows子對象包含2個子節點:Id和cell,Id表示當前數據行的Id,cell表示在前端需要展示的數據的值,其順序與前端代碼的顯示順序一一對應。
下面我把組裝Flexigrid格式的Json方法貼上:
/// <summary> /// 將list轉換成FlexiGrid約定格式的Json /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="page">當前頁數</param> /// <param name="total">總量</param> /// <returns></returns> public static string GetFlexiGridJson<T>(List<T> obj, int page, int total) { string json = "page:{0},total:{1},rows:[{2}]"; StringBuilder value = new StringBuilder(); PropertyInfo[] propinfos = null; foreach (var i in obj) { StringBuilder input = new StringBuilder(); if (propinfos == null) { propinfos = i.GetType().GetProperties(); } foreach (PropertyInfo j in propinfos) { if (j.Name.ToLower() == "id") { input.AppendFormat("{0}:'{1}',cell:[", j.Name, j.GetValue(i, null)); } input.AppendFormat("'{0}',", j.GetValue(i, null)); } input.Remove(input.Length - 1, 1); input.AppendFormat("]"); value.AppendFormat("{0},", "{" + input.ToString() + "}"); } value.Remove(value.Length - 1, 1); json = "{" + string.Format(json, page, total, value) + "}"; return json; }
FlexiGrid的數據交互最重要的就是其JSON格式的組裝。
下面貼上關於FlexiGrid的參數說明:
height: 200, //flexigrid插件的高度,單位為px width: 'auto', //寬度值,auto表示根據每列的寬度自動計算,在IE6下建議設置具體值否則會有問題 striped: true, //是否顯示斑紋效果,默認是奇偶交互的形式 novstripe: false,//沒用過這個屬性 minwidth: 30, //列的最小寬度 minheight: 80, //列的最小高度 resizable: false, //resizable table是否可伸縮 url: false, //ajax url,ajax方式對應的url地址 method: 'POST', // data sending method,數據發送方式 dataType: 'json', // type of data loaded,數據加載的類型,xml,json errormsg: '發生錯誤', //錯誤提升信息 usepager: false, //是否分頁 nowrap: true, //是否不換行 page: 1, //current page,默認當前頁 total: 1, //total pages,總頁面數 useRp: true, //use the results per page select box,是否可以動態設置每頁顯示的結果數 rp: 25, // results per page,每頁默認的結果數 rpOptions: [10, 15, 20, 25, 40, 100], //可選擇設定的每頁結果數 title: false, //是否包含標題 pagestat: '顯示記錄從{from}到{to},總數 {total} 條', //顯示當前頁和總頁面的樣式 procmsg: '正在處理數據,請稍候 ...', //正在處理的提示信息 query: '', //搜索查詢的條件 qtype: '', //搜索查詢的類別 qop: "Eq", //搜索的操作符 nomsg: '沒有符合條件的記錄存在', //無結果的提示信息 minColToggle: 1, //允許顯示的最小列數 showToggleBtn: true, //是否允許顯示隱藏列,該屬性有bug設置成false點擊頭腳本報錯。 hideOnSubmit: true, //是否在回調時顯示遮蓋 showTableToggleBtn: false, //是否顯示【顯示隱藏Grid】的按鈕 autoload: true, //自動加載,即第一次發起ajax請求 blockOpacity: 0.5, //透明度設置 onToggleCol: false, //當在行之間轉換時,可在此方法中重寫默認實現,基本無用 onChangeSort: false, //當改變排序時,可在此方法中重寫默認實現,自行實現客戶端排序 onSuccess: false, //成功后執行 onSubmit: false, // 調用自定義的計算函數,基本沒用 //Style gridClass: "bbit-grid"//樣式 }, p); ---------------------------------------------------------------------------------------------- 2、支持ajax跨域: url中加callback=? 后台獲得callback函數的名字 返回json數據格式為:print(callbackName+"("+jsonString+")"); ---------------------------------------------------------------------------------------------- 3、Flexigrid(HUGO.CM修改版v1.1)使用說明: 1、加載flexigrid。p:選項參數集合 $(“”).flexigrid(p); 2、重新加載數據。 $(“”).flexReload(p); 3、更改flexigrid參數。P:選項參數集合 $(“”).flexOptions (p); 4、隱藏/顯示列。cid:列索引,visible:bool $(“”).flexToggleCol (cid, visible); 5、綁定數據。Data:數據源 $(“”).flexAddData (data); 6、no select plugin by me 。不知道做什么用的 $(“”).noSelect (p); 7、重新指定寬度和高度。 $(“”).flexResize(w,h); 8、翻頁。type:first、prev、next、last、input $(“”).changePage(type); ---------------------------------------------------------------------------------------------- 4、Flexigrid——colModel: 屬性名 類型 描述 display string 顯示的列名 name string 綁定的列名 sortable bool 是否可以排序 align string 對其方式 width int 列的寬度 hide bool 是否隱藏該列 pk bool 是否為主鍵標識、如果是則隱藏該列,值存入隱藏域中 process function customValue function 自定義顯示值。(如性別:數據庫為Bit類型,通過customValue方法返回“男/女”)參數:value,i ---------------------------------------------------------------------------------------------- 5、Flexigrid——事件 事件名 參數 描述 返回值 onDragCol dcoln,dcolt 拖動列后觸發 無 onToggleCol cid,visible 隱藏/顯示列后觸發 無 onChangeSort sortname,sortorder 自定義排序事件 無 onChangePage newp 自定義翻頁事件 無 onSuccess 無 數據獲取成功時觸發 無 onError XMLHttpRequest,textStatus,errorThrown 出現錯誤時觸發 無 onSubmit 無 在獲取數據前時觸發 bool onRowSelect this 行選中事件 無 ---------------------------------------------------------------------------------------------- 6、Flexigrid——buttons 屬性名 類型 描述 name string 按鈕名稱 bgclass string 樣式 onpress function 點擊觸發的方法 separator bool 分割線 ---------------------------------------------------------------------------------------------- 7、Flexigrid——searchitems 屬性名 類型 描述 display string 搜索類型下拉列表框:顯示的列名 name string 搜索類型下拉列表框:綁定的列名 isdefault bool 是否為默認搜索類型 //注:如果searchitems:true,則自動根據所有字段生成下拉列表框
示例:
1:在html中引用Jquery,FlexiGrid以及css:
<link href="@Url.Content("~/Scripts/Assets/FlexiGrid(1.8.3JQ)/css/flexigrid.pack.css")" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="@Url.Content("~/Scripts/Assets/FlexiGrid(1.8.3JQ)/flexigrid.js")" type="text/javascript"></script>
2:配置FlexiGrid(以下參數配置請參加博客的參數列表)
<script type="text/javascript"> $(document).ready(function () { $("#TbInvitationCode").flexigrid({ url: "MembershipManager/GetInvitationCode?UseState=3&r=" + Date().toLocaleString(), dataType: "json", height: "auto", width: "auto", usepager: true, title: "邀請碼", showtogglebtn: true, userp: true, rp: 20, sortder: "asc", sortname: "iso", pagestat: '顯示記錄從{from}到{to},總數 {total} 條', nomsg: '沒有符合條件的記錄存在', errormsg: '運行錯誤', hideOnSubmit: true, colModel: [ { display: 'ID', name: 'id', sortable: true, align: 'center' }, { display: '授權郵箱', name: 'Email', sortable: true, align: 'center' }, { display: '發送日期', name: 'CreateDate', sortable: true, align: 'center' }, { display: '注冊日期', name: 'ActivationDate', sortable: true, align: 'center' }, ], buttons: [{ name: 'Add', bclass: 'add', onpress: undefined }, { name: 'Delete', bclass: 'delete', onpress: undefined }, { separator: true}], searchitems: [{ display: '授權郵箱', name: 'Email' }, { display: 'Name', name: 'name', isdefault: true}] }); }); </script>
如上配置:
colModel負責顯示數據,其順序對應JSON中Rows子對象的順序,display表示顯示的列名,sortable表示此列具備排序功能,hide表示此列是否顯示(true/false),align表示字符對齊方式。
3:C# Json輸出Action
public class MembershipManagerController : Controller { // // GET: /MembershipManager/ public ActionResult Index() { return View(); } public ActionResult SendInvitationCode() { return View(); } public string GetInvitationCode() { int id = Convert.ToInt32(User.Identity.Name); int page = Convert.ToInt32(InputOperation.GetUriRequest("page")); UseState state = (UseState)Convert.ToInt32(InputOperation.GetUriRequest("UseState")); IInvitationCodeRepository Repository = ObjectContainerFactory.ObjectContainer.Resolve<IInvitationCodeRepository>(); FlexiGridPager F = new FlexiGridPager(id,state); var list = Repository.GetInvitationCode(F); string json = JsonHelper.GetFlexiGridJson<InvitationCode>(list, page, list.Count); return json; } }
public class JsonHelper { /// <summary> /// 將list轉換成FlexiGrid約定格式的Json /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="page">當前頁數</param> /// <param name="total">總量</param> /// <returns></returns> public static string GetFlexiGridJson<T>(List<T> obj, int page, int total) { string json = "page:{0},total:{1},rows:[{2}]"; StringBuilder value = new StringBuilder(); PropertyInfo[] propinfos = null; foreach (var i in obj) { StringBuilder input = new StringBuilder(); if (propinfos == null) { propinfos = i.GetType().GetProperties(); } foreach (PropertyInfo j in propinfos) { if (j.Name.ToLower() == "id") { input.AppendFormat("{0}:'{1}',cell:[", j.Name, j.GetValue(i, null)); } input.AppendFormat("'{0}',", j.GetValue(i, null)); } input.Remove(input.Length - 1, 1); input.AppendFormat("]"); value.AppendFormat("{0},", "{" + input.ToString() + "}"); } value.Remove(value.Length - 1, 1); json = "{" + string.Format(json, page, total, value) + "}"; return json; }
4:經過以上代碼,可以將JSON字符串發送到客戶端,但筆者發現,Flexigrid對於JSON數據獲取時的AJAX方法的Success事件並不能接收到JSON字符串,所以理改Flexigrid插件如下:
$.ajax({ type: p.method, url: p.url, data: param, dataType: "html",//原為p.datatype success: function (data) { data = eval("(" + data + ")");//筆者增加 g.addData(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { try { if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown); } catch (e) {} } });
最終效果:
因為案例導出不易,所以未能添加實際案例下載,請見諒。若有疑問請聯系。
更多WEB開發技術請加群:Asp.Net高級群 號碼:261882616 博主以及同事和你共同探討感興趣的話題。