最近项目中用到了BootStrap做后台,在选择表格插件的时候发现了jquery datatables。
功能是很强大,但是网上的例子比较少。在经过一段时间的努力可算是搞出来了。
官网地址:http://www.datatables.net/
官网上的例子比较简单,基础的介绍还是要看看的。
效果图
引入相应css 和js
<link href="http://cdn.datatables.net/1.10.5/css/jquery.dataTables.css" rel="stylesheet" /><script src="http://code.jquery.com/jquery-1.11.1.min.js"></script><script src="http://cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>
页面HTML
<div class="portlet-body p10"><div class="form-body "><div class="row"><div class="col-md-5"><div class="form-group"><label class="control-label col-md-3">User Name: </label><div class="col-md-6"><input id="txt_UserName" name="txt_UserName" type="text" value="" /><span class="help-block">This is inline help </span></div></div></div><!--/span--><div class="col-md-5"><div class="form-group"><label class="control-label col-md-4">Division:</label><div class="col-md-6 form-inline"><select id="Sel_Division" name="Gender"><option value="">全部</option><option value="A">A</option><option value="B">B</option></select></div></div></div><!--/span--></div><div class="row"><div class="col-md-5"></div><!--/span--><div class="col-md-5"><div class="form-group"><button type="submit" id="btn_Search" class="btn green">Search</button></div></div><!--/span--></div></div></div><div class="portlet-body p10"><table class="table table-striped table-bordered table-hover" id="UserList"><thead><tr><th>User ID</th><th>User Ename</th><th>AD Account</th><th>User Email</th><th>Division</th><th>Entity</th><th>IsValid</th><th>Operation</th></tr></thead></table></div>
我这里用到的是 服务器端处理。(很少有人把数据全部取出来,让js 处理的吧。。。)
JS 代码 初始化
var oTable = null; var initUserList = function () {var table = $('#UserList'); if (oTable == null) { //仅第一次检索时初始化Datatable oTable = table.dataTable({"bLengthChange": false, //改变每页显示数据数量"bFilter": false, //过滤功能"bProcessing": true, //开启读取服务器数据时显示正在加载中……特别是大数据量的时候,开启此功能比较好"bServerSide": true, //开启服务器模式,使用服务器端处理配置datatable。注意:sAjaxSource参数也必须被给予为了给datatable源代码来获取所需的数据对于每个画。 这个翻译有点别扭。"iDisplayLength": 10,//每页显示10条数据//ajax地址 "sAjaxSource": "/Home/Home/GetUserList",// get地址//"sAjaxSource": "/Home/Home/UserListPost",// post地址"fnServerData": retrieveData,//执行方法//默认排序"order": [[0, 'asc']//第一列正序 ],"lengthMenu": [[5, 15, 20, -1],[5, 15, 20, "All"] // change per page values here ],// set the initial value"pageLength": 10,//向服务器传额外的参数"fnServerParams": function (aoData) {aoData.push({ "name": "UserName", "value": $('#txt_UserName').val() },//员工名字{ "name": "Division", "value": $('#Sel_Division').val() })//所处Division},//配置列要显示的数据"columns": [{ "data": "User_ID" },{ "data": "User_Ename" },{ "data": "AD_Account" },{ "data": "User_Email" },{ "data": "Division" },{ "data": "Entity" },{ "data": "IsValid" },{ "data": "" }//操作按钮列],//按钮列"columnDefs": [//{// "targets": -2,//编辑// "data": null,// "defaultContent": "<button id='editrow' class='btn btn-primary' type='button'><i class='fa fa-edit'></i></button>"//}, {"targets": -1,//删除"data": null,"defaultContent": "<button id='editrow' class='btn btn-primary' type='button'><i class='fa fa-edit'></i></button><button id='delrow' class='btn btn-primary' type='button'><i class='fa fa-trash-o'></i></button>"}] ,//语言配置--页面显示的文字"language": {"aria": {"sortAscending": ": activate to sort column ascending","sortDescending": ": activate to sort column descending"},"emptyTable": "No data available in table","info": "Showing _START_ to _END_ of _TOTAL_ entries","infoEmpty": "No entries found","infoFiltered": "(filtered1 from _MAX_ total entries)","lengthMenu": "Show _MENU_ entries","search": "Search:","zeroRecords": "No matching records found"}});}//刷新Datatable,会自动激发retrieveData oTable.fnDraw();// tableWrapper.find('.dataTables_length select').select2(); // initialize select2 dropdown }
function retrieveData(sSource, aoData, fnCallback) {/* get 方法调用*/$.ajax({"type": "get","contentType": "application/json","url": sSource,"dataType": "json","data": aoData, "success": function (resp) {fnCallback(resp); //服务器端返回的对象的returnObject部分是要求的格式 }});/* Post 方法调用$.ajax({"type": "post","url": sSource,"dataType": "json","data": aoData,"success": function (resp) {fnCallback(resp); //服务器端返回的对象的returnObject部分是要求的格式 }});*/ }
jQuery(document).ready(function () {initUserList()//搜索$("#btn_Search").click(function () {initUserList()})//按钮的绑定事件要放到document或者其他父标签上,因为元素是在datatable方法加载完成之后才显示出来的//编辑$(".portlet-body").on('click', 'button#editrow', function () {var data = $("#UserList").DataTable().row($(this).parents("tr")).data();alert(data.User_Ename + "'s Division is: " + data.Division);});//删除$(".portlet-body").on('click', 'button#delrow', function () {var data = $("#UserList").DataTable().row($(this).parents("tr")).data();alert("Do you want delete " + data.User_Ename + "?");});});
后台代码
开启后台处理之后,每次翻页、排序都会调用代码中配置的地址:/Home/Home/GetUserList
回传很多参数,我们这里只用到这几个:
页面大小:iDisplayLength
开始数:iDisplayStart(是开始数不是当前页数...)
要排序的列序号:iSortCol_0(从零开始)
正序还是倒序:sSortDir_0(desc or asc)
获取第一列列明:mDataProp_0(从零开始)
好了上代码
[HttpGet]public string GetUserList(){//JsonConvert.PopulateObject(var re = new UserRequest();//获取页面大小if (string.IsNullOrWhiteSpace(Request["iDisplayLength"]))re.PageSize = 10; elsere.PageSize = int.Parse(Request["iDisplayLength"]);//获取开始数 算出当前页数if (string.IsNullOrWhiteSpace(Request["iDisplayStart"]))re.PageIndex = 1; elsere.PageIndex = (int.Parse(Request["iDisplayStart"]) / re.PageSize) + 1;//自定义的两个参数 Division和UserNameif (!string.IsNullOrWhiteSpace(Request["Division"]))re.Division = Request["Division"];if (!string.IsNullOrWhiteSpace(Request["UserName"]))re.User_Ename = Request["UserName"];//排序if (!string.IsNullOrWhiteSpace(Request["iSortCol_0"]) && !string.IsNullOrWhiteSpace(Request["sSortDir_0"]))re.OrderBy = Request[("mDataProp_" + Request["iSortCol_0"])];// +" " + Request["sSortDir_0"];elsere.OrderBy = Request[("mDataProp_0")];//正序还是倒序if(!string.IsNullOrWhiteSpace(Request["sSortDir_0"]))re.Isdesc=(Request["sSortDir_0"]=="descdesc"?true:false);var result = new DataResult();var data = this.AccountService.GetUserList(re);//获取数据的方法result.recordsTotal = data.TotalItemCount;result.recordsFiltered = data.TotalItemCount;result.data = data;return JsonConvert.SerializeObject(result);}
public class UserRequest : Request{public UserRequest() { Isdesc = false; }public string User_Ename { get; set; }public string Division { get; set; }public bool IsValid { get; set; }public long User_ID { get; set; }public string OrderBy { get; set; }public bool Isdesc { get; set; }}
public class DataResult{public int draw { get; set; }public int recordsTotal { get; set; }public int recordsFiltered { get; set; }public object data;}
基本就这些了。嘿嘿,本人技术稀烂,大神见笑了。