最近项目中用到了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 = ;
else
re.PageSize = int.Parse(Request["iDisplayLength"]); //获取开始数 算出当前页数
if (string.IsNullOrWhiteSpace(Request["iDisplayStart"]))
re.PageIndex = ;
else
re.PageIndex = (int.Parse(Request["iDisplayStart"]) / re.PageSize) + ; //自定义的两个参数 Division和UserName
if (!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"];
else
re.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;
}

 

基本就这些了。嘿嘿,本人技术稀烂,大神见笑了。

jquery datatables 学习笔记的更多相关文章

  1. jQuery源代码学习笔记_工具函数_noop/error/now/trim

    jQuery源代码学习笔记_工具函数_noop/error/now/trim jquery提供了一系列的工具函数,用于支持其运行,今天主要分析noop/error/now/trim这4个函数: 1.n ...

  2. jQuery的学习笔记4

    JQuery学习笔记3 2.9属性选择器 属性选择器就是根据元素的属性和属性值作为过滤条件,来匹配对应的DOM元素.属性选择器一般都以中括号作为起止分界符 它的形式如下: [attribute] [a ...

  3. jQuery的学习笔记2

    jQuery学习笔记 Day two Chapter two 选择器 类选择器 语法结构:$(“.classname”) javascript里面没有类选择器所以这个时候使用jQuery会更加的简便 ...

  4. jQuery的学习笔记

    JQuery学习笔记 Chapter one初识jQuery 1.2测试jQuery 在jQuery库中,$是jQuery的别名,如:$()相当于jQuery() 注意:在使用JQuery进行开发的时 ...

  5. jQuery 基础学习笔记总结(一)

    Jquery 学习笔记 总结 感想: 此前在做站点时用到过jquery相关,特别是Ajax相关技术.但是并没有系统的进行学习和了解Jquery的强大的功能,趁这几天跟着资料基本的了解下Jquery的特 ...

  6. JQuery DataTables学习

    1.Datatables简单介绍 DataTables是一个jQuery的表格插件.这是一个高度灵活的工具,根据的基础逐步增强,这将添加先进的互动控制.支持不论什么HTML表格. 主要特点: 自己主动 ...

  7. Jquery Mobile 学习笔记(一)

    1.模拟器,IOS:XCODE GENYMOTION  ANDROID:ECLIPSE GENYMOTION 2.jquery mobile data-role=page 代表一个页面 data-po ...

  8. 【jQuery UI 1.8 The User Interface Library for jQuery】.学习笔记.4.Tabs控件

    之前,我们已经介绍了 jQuery UI 库,CSS 框架.下面,我们将学习这些有增强可视化效果,高度可配置的用户交互组件. Tab 的特性是,点击 tab 后,会高亮该 tab,并显示他的关联con ...

  9. Jquery mobile 学习笔记

    最近学习移动开发,接触到了phonegap,然后又需要开始学习jquery mobile.掌握两者是开发轻应用的前提 在学习jquery mobile中,遇到了许多问题让初学者很是头疼,无意间找到这个 ...

随机推荐

  1. 【OCP-12c】2019年CUUG OCP 071考试题库(77题)

    77.Which two statements are true about sequences created in a single instance database? (Choose two. ...

  2. 【awk】按小时切割日志

    需求: 把日志按日志内容中的小时数做切割 {hostname=ali-beijing-msync-3512} 2017-05-17 23:17:52.694 [info] <0.27292.70 ...

  3. Performs the analysis process on a text and return the tokens breakdown of the text

    Analyzeedit Performs the analysis process on a text and return the tokens breakdown of the text. Can ...

  4. CentOS6.5下telnet服务

    00×0 本文介绍Telnet搭建,以及展示这是一个不安全的远程服务. 00×1 服务准备工作 [root@localhost ~]# yum install xinetd telnet-server ...

  5. CentOS下安装Docker

    简介:本篇文章介绍如何在CentOS系统下面安装docker系统. 官方文档:https://docs.docker.com/install/linux/docker-ce/centos/ Docke ...

  6. Web安全篇之SQL注入攻击

    在网上找了一篇关于sql注入的解释文章,还有很多技术,走马观花吧 文章来源:http://www.2cto.com/article/201310/250877.html ps:直接copy,格式有点问 ...

  7. .NET中的async和await关键字使用及Task异步调用实例

    其实早在.NET 4.5的时候M$就在.NET中引入了async和await关键字(VB为Async和Await)来简化异步调用的编程模式.我也早就体验过了,现在写一篇日志来记录一下顺便凑日志数量(以 ...

  8. RocketMQ之NameServer学习笔记

    org.apache.rocketmq.namesrv.NamesrvController NameserController,NameServer的核心控制类. 1.1 NamesrvConfig ...

  9. 思维题--code forces round# 551 div.2

    思维题--code forces round# 551 div.2 题目 D. Serval and Rooted Tree time limit per test 2 seconds memory ...

  10. c# 获取项目根目录方法

    编写程序的时候,经常需要用的项目根目录.自己总结如下 1.取得控制台应用程序的根目录方法     方法1.Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径 ...