Datatables.js在asp.net mvc5中的使用
程序员文章站
2024-02-29 20:33:34
...
实体层
Area.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcDemo.Models
{
public class Area
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double PointX { get; set; }
public double PointY { get; set; }
public IQueryable<Area> GetData()
{
var data = new List<Area>();
for (var i = 1; i <= 100; i++)
{
data.Add(new Area() { Id = i, Name = "村" + i, Description = "这里是村" + i, PointX = i + 119.082458, PointY = i + 36.925349 });
}
return data.AsQueryable();
}
}
}
AreaQuery.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcDemo.Models.DataTables;
namespace MvcDemo.Models
{
public class AreaQuery : DataTablesParameters
{
public string Name { get; set; }
public string Description { get; set; }
public double X { get; set; }
public double Y { get; set; }
}
}
控制器层
DataTablesController.cs
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web.Mvc;
using MvcDemo.Models;
using MvcDemo.Models.DataTables;
namespace MvcDemo.Controllers
{
public class DataTablesController : Controller
{
public ActionResult DataTables()
{
return PartialView();
}
public JsonResult GetDatas(AreaQuery query)
{
var data = new Area().GetData();
if (!string.IsNullOrEmpty(query.Name))
data = data.Where(n => n.Name.Contains(query.Name));
if (!string.IsNullOrEmpty(query.Description))
data = data.Where(n => n.Description.Contains(query.Description));
if (query.X > 0)
data = data.Where(n => Equals(n.PointX, query.X));
if (query.Y > 0)
data = data.Where(n => Equals(n.PointY, query.Y));
data = data.OrderBy(query.OrderBy, query.OrderDir == DataTablesOrderDir.Desc);
var count = data.Count();
var result = data.Skip(query.Start).Take(query.Length).ToList();
return DataTablesJson(query.Draw, count, count, result);
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="draw">请求次数计数器</param>
/// <param name="recordsTotal">总共记录数</param>
/// <param name="recordsFiltered">过滤后的记录数</param>
/// <param name="data">数据</param>
/// <param name="error">服务器错误信息</param>
public JsonResult DataTablesJson<TEntity>(int draw, int recordsTotal, int recordsFiltered,
IReadOnlyList<TEntity> data, string error = null)
{
var result = new DataTablesResult<TEntity>(draw, recordsFiltered, recordsFiltered, data);
var jsonResult = new JsonResult
{
Data = result
};
return jsonResult;
}
}
}
视图层
DataTables.cshtml
@{
ViewBag.Title = "DataTables";
//bootstrap的css
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
//这里我们使用bootstrap的主题,其他的请对号入座
<link href="~/Scripts/DataTables-1.10.10/media/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
//bootstrap主题的js
<script src="~/Scripts/DataTables-1.10.10/media/js/jquery.dataTables.min.js"></script>
//核心js
<script src="~/Scripts/DataTables-1.10.10/media/js/dataTables.bootstrap.js"></script>
//修改默认的一些配置
<script src="~/Scripts/DataTables.js"></script>
<script src="~/Scripts/moment-with-locales.js"></script>
}
<section>
<div class="row" style="margin-top:50px;">
<div class="col-lg-offset-2 col-lg-8">
<div class="form-group col-lg-12">
<div class="col-lg-3">
<input type="text" placeholder="名称" id="name" class="form-control">
</div>
<div class="col-lg-3">
<input type="text" placeholder="描述" id="desc" class="form-control">
</div>
<div class="col-lg-2">
<input type="text" placeholder="X" id="x" class="form-control">
</div>
<div class="col-lg-2">
<input type="text" placeholder="Y" id="y" class="form-control">
</div>
<div class="col-lg-2">
<button id="hehe" class="btn btn-warning pull-right" type="button"><i class="fa fa-search"></i> 搜 索</button>
</div>
</div>
<table id="area" class="table table-striped table-bordered" data-page-length="10" data-order="[[0,"asc"]]" width="100%">
<thead>
<tr>
<th data-data="Id" data-visible="false">Id</th>
<th data-orderable="false"><input type="checkbox" id="checkbox-all" /></th>
<th data-data="Name">名称</th>
<th data-data="Description" data-orderable="false">描述</th>
<th data-data="PointX">坐标</th>
<th data-orderable="false">操作</th>
</tr>
</thead>
</table>
</div>
</div>
</section>
<script>
$(function () {
console.log(moment().format('LL'));
var areaTable = $('#area').dataTable({
"ajax": {
"url": "@Url.Action("GetDatas", "DataTables")",
"data": function (data) {
//添加额外的参数传给服务器
data.Name = $("#name").val();
data.Description = $("#desc").val();
data.X = $("#x").val();
data.Y = $("#y").val();
return JSON.stringify(data);
}
},
"columnDefs": [{
"targets": 1,
"width": "15px",
render: function (data, type, full, meta) {
return '<input type="checkbox" id="checkbox-all-' + full.Id + '" value="' + full.Id + '" />';
}
},
{
"targets": 4,
render: function (data, type, full, meta) {
return full.PointX + "," + full.PointY;
}
},
{
"targets": -1,
"width": "100px",
render: function (data, type, full, meta) {
return '<a class="btn btn-sm btn-info" href="javascript:;">设置<i class="fa fa-cogs"></i></a> ' +
'<a class="btn btn-sm btn-info" href="javascript:;">删除<i class="fa fa-trash"></i></a>';
}
}]
});
$("#hehe").click(function () {
areaTable.api().ajax.reload();
});
});
</script>
DataTables.js
$.extend($.fn.dataTable.defaults, {
"dom": "<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 text-center'i>>" +
"<'row'<'col-sm-5'l><'col-sm-7'p>>",//默认是lfrtip
"processing": true,//加载中
"serverSide": true,//服务器模式
"searching": false,//datatables自带的搜索
"scrollX": true,//X滑动条
"pagingType": "full_numbers",//分页模式
"ajax": {
"type": "POST",
"contentType": "application/json; charset=utf-8"
},
"language": {
"processing": "加载中...",
"lengthMenu": "每页显示 _MENU_ 条数据",
"zeroRecords": "没有匹配结果",
"info": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
"infoEmpty": "显示第 0 至 0 项结果,共 0 项",
"infoFiltered": "(由 _MAX_ 项结果过滤)",
"infoPostFix": "",
"search": "搜索:",
"url": "",
"emptyTable": "没有匹配结果",
"loadingRecords": "载入中...",
"thousands": ",",
"paginate": {
"first": "首页",
"previous": "上一页",
"next": "下一页",
"last": "末页"
},
"aria": {
"sortAscending": ": 以升序排列此列",
"sortDescending": ": 以降序排列此列"
}
}
});
$(function () {
$("#checkbox-all").prop("checked", false);
$("body").on("change", "#checkbox-all", function () {
var checked = $("#checkbox-all").is(":checked");
$("input[id^='checkbox-all-']").each(function () {
if (checked) {
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
});
});
dataTable和DataTable的区别
1.10.x版本后,有两种初始化的写法,
$().dataTable()
返回的是一个jQuery实例,$().DataTable()
返回的是Datatables的api实例,如果在使用过程中出现某某方法不存在不支持之类的,一般都是由于是用第一种方法初始化dt,用返回的对象去调用api的方法,所以报错误。
dt的api实例和jquery可以互转 ,jquery转api:dt.api();
api转jquery:dt.to$();
详细参考api手册
服务器端获取Datatables的请求参数
当使用服务器处理时,dt会发送如下数据给服务器
名称 | 类型 | 描述 |
---|---|---|
draw | integerJS | 请求次数计数器,每次发送给服务器后又原封返回. |
start | integerJS | 第一条数据的起始位置,比如0代表第一条数据 |
length | integerJS | 每页显示的条数. |
search[value] | stringJS | 全局的搜索条件,针对于每一列( searchable需要设置为 true ) |
search[regex] | booleanJS | 如果为 true代表全局搜索的值是作为正则表达式处理,为 false则不是。 |
order[i][column] | integerJS | i是一个数组索引,对应的是 columns,从0开始,次参数表示那一列需要排序 |
order[i][dir] | stringJS | 上面确定了是那一列,这个确定对应的列是什么样的排序方式 desc 是降序 asc升序 |
columns[i][data] | stringJS | columns 绑定的数据源,由 columns.data 定义 |
columns[i][name] | stringJS | columns.name 里定义的名称 |
columns[i][searchable] | booleanJS | 标记列是否能被搜索 为 true代表可以,否则不可以,这个是由 columns.searchable 控制 |
columns[i][orderable] | booleanJS | 标记列是否能排序 为 true代表可以,否则不可以,这个是由 columns.orderabl 控制 |
columns[i][search][value] | stringJS | 特定列的搜索条件 |
columns[i][search][regex] | booleanJS | 特定列的搜索条件是否视为正则表达式 |