.
NET MVC 学习笔记(三)—— MVC 数据显示
在目前做的项目中,用的最多的数据展示控件就是table展示(说不是的请走开,不是一路人),以下详细阐述下table的使用方法。
先看效果:
上图中包含两个部分,上面的是检索区域,下面部分是数据显示区域。检索区域不做讨论,主要看数据显示部分。
数据显示部分包含三部分:【功能按钮】、【数据表】、【分页信息】
功能按钮:是关于数据的操作,新增,删除等
数据表:显示数据
分页信息:对查询的数据进行分页显示,包括前端分页和服务器分页两种,这里我们用服务器端分页,提高检索速度
这里介绍数据表的加载功能。
页面加载过程中,数据表显示初始化:
页面部分代码:
<div class="box-header" id="toolbar">
<div class="btn-group">
<button type="button" class="btn btn-default" id="btnAdd">新增会员</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-default" id="btnDelete">删除会员</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-default" id="btnDownloadTemplate">下载模板</button>
</div>
<div class="btn-group" style="text-align:right;width:82px">
<label class="input-group-btn">
<input id="btnSelectData" type="file" name="file" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style="left: -9999px; position: absolute;">
<span class="btn btn-default" style="border-radius:3px">导入会员</span>
</label>
</div>
</div>
<div class="box-body">
<table id="tb_Client"></table>
</div>
JS代码:
$(function () {
//1.初始化Table
var oTable = new TableInit();
oTable.Init(); //2.初始化Button的点击事件
var oButtonInit = new ButtonInit();
oButtonInit.Init();
});
var TableInit = function () {
var oTableInit = new Object();
//初始化Table
oTableInit.Init = function () {
$('#tb_Client').bootstrapTable({
url: '@Url.Content("~/Client/GetClientList")', //请求后台的URL(*)
method: 'post', //请求方式(*)
toolbar: '#toolbar', //工具按钮用哪个容器
striped: false, //是否显示行间隔色
cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
pagination: true, //是否显示分页(*)
sortable: false, //是否启用排序
sortOrder: "asc", //排序方式
queryParams: oTableInit.queryParams,//传递参数(*)
sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*)
pageNumber: 1, //初始化加载第一页,默认第一页
pageSize: 10, //每页的记录行数(*)
pageList: [10, 25, 50, 100], //可供选择的每页的行数(*)
search: false, //是否显示表格搜索,此搜索是会员端搜索,不会进服务端,所以,个人感觉意义不大
strictSearch: true,
showColumns: false, //是否显示所有的列
showRefresh: false, //是否显示刷新按钮
minimumCountColumns: 2, //最少允许的列数
clickToSelect: true, //是否启用点击选中行
uniqueId: "Id", //每一行的唯一标识,一般为主键列
showToggle: false, //是否显示详细视图和列表视图的切换按钮
cardView: false, //是否显示详细视图
detailView: false, //是否显示父子表
columns: [{
checkbox: true
}, {
field: 'CardNo',
name: 'CardNo',
align: table_align,
title: '会员卡号'
}, {
field: 'UserName',
name: 'UserName',
align: table_align,
title: '会员名'
}, {
field: 'Sex',
name: 'Sex',
align: table_align,
title: '性别'
}, {
field: 'Birthdate',
name: 'Birthdate',
align: table_align,
title: '出生日期',
//获取日期列的值进行转换
formatter: function (value, row, index) {
return changeDateFormat(value, "YYYY-MM-DD")
}
}, {
field: 'Phone',
name: 'Phone',
title: '手机号',
align: table_align
}, {
field: 'Address',
name: 'Address',
title: '地址',
align: table_align
}, {
field: 'Score',
name: 'Score',
title: '积分',
align: table_align
}, {
field: 'GradeText',
name: 'GradeText',
title: '等级',
align: table_align
}, {
field: 'operate',
title: '编辑',
align: 'center',
events: operateEvents,
width: '8%',
formatter: operateFormatter
}]
});
}; //得到查询的参数
oTableInit.queryParams = function (params) {
var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
PageSize: params.limit, //页面大小
Offset: params.offset / params.limit + 1, //页码
CardNo: $("#txtCardNo").val(),
UserName: $("#txtClientName").val(),
Phone: $("#txtPhone").val()
};
return temp;
};
return oTableInit;
}; var ButtonInit = function () {
var oInit = new Object();
var postdata = {}; oInit.Init = function () {
//初始化页面上面的按钮事件
$("#btnAdd")
.click(function () {
$("#myModalLabel").text("新增会员");
var options = {
Id: "",
CardNo: "",
UserName: "",
Sex: "",
Birthdate: "",
Phone: "",
Address: "",
Score: "",
GradeCode: ""
};
setFormValue(options);
$('#myClientModal').modal();
});
$("#btnDelete")
.click(function () {
removeRows();
});
$("#btnDownloadTemplate")
.click(function () {
window.location.href = "@Url.Content("~/Content/ImportClientDataTemplate.xlsx")";
});
}; return oInit;
}; function operateFormatter(value, row, index) {
return [
'<a class="edit" style="cursor: pointer" href="javascript:void(0)" title="编辑">',
'<i class="fa fa-edit"></i>',
'</a>'
].join('');
} window.operateEvents = {
'click .edit': function (e, value, row, index) {
editRow(row);
}
};
// 表格数据对应方式
var table_align = "left"; //转换日期格式(时间戳转换为datetime格式)
function changeDateFormat(cellval, dateType) {
var dateVal = cellval + "";
if (cellval != null) {
var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
if (dateType == "YYYY-MM-DD") {
return date.getFullYear() + "-" + month + "-" + currentDate;
}
else if (dateType == "YYYY-MM-DD HH:MM:SS") {
return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
}
}
}
后台代码:
/// <summary>
/// 获取会员列表
/// </summary>
/// <param name="filter">查询条件</param>
/// <returns>会员列表</returns>
[HttpPost]
public JsonResult GetClientList(ClientFilter filter)
{
// 检索条件
filter.SortField = "CardNo ASC";
filter.StartRowIndex = filter.Offset - 1;
// get Client list
var result = service.GetClientList(filter);
var resObj = new TableData();
foreach (var item in result)
{
resObj.total = item.Key;
resObj.rows = item.Value;
}
return Json(resObj, JsonRequestBehavior.AllowGet);
}
ClientFilter.cs
namespace CRM.Entity
{
/// <summary>
/// create by: Pegasus
/// Filter
/// </summary>
[Serializable]
[DataContract]
public class ClientFilter : ClientModel
{
#region Private Fields
private String swhere;
private String sortField;
private Int32 startRowIndex;
private Int32 maximumRows;
private Int32 totalRows;
private Int32 pageSize;
private Int32 offset; private DateTime? birdateStart; private DateTime? birdateEnd; private DateTime? createDateTimeStart; private DateTime? createDateTimeEnd; private DateTime? updateDateTimeStart; private DateTime? updateDateTimeEnd; #endregion #region Attributes
/// <summary>
/// Special Property for "SQL Where" Component
/// </summary>
[DataMember]
public String sWhere
{
set
{
swhere = value;
}
get
{
return swhere;
}
} /// <summary>
/// Sort Field
/// </summary>
[DataMember]
public String SortField
{
set
{
sortField = value;
}
get
{
return sortField;
}
} /// <summary>
/// Start row index
/// </summary>
[DataMember]
public Int32 StartRowIndex
{
get
{
return startRowIndex;
}
set
{
startRowIndex = value;
}
} /// <summary>
/// Maximum return ows
/// </summary>
[DataMember]
public Int32 MaximumRows
{
get
{
return maximumRows;
}
set
{
maximumRows = value;
}
} /// <summary>
/// Total Rows
/// </summary>
[DataMember]
public Int32 TotalRows
{
get
{
return this.totalRows;
}
set
{
this.totalRows = value;
}
} /// <summary>
/// Page Size 页面大小
/// for bootstrap table
/// </summary>
[DataMember]
public Int32 PageSize
{
get
{
return this.pageSize;
}
set
{
this.pageSize = value;
}
} /// <summary>
/// Offset 页码
/// for bootstrap table
/// </summary>
[DataMember]
public Int32 Offset
{
get
{
return this.offset;
}
set
{
this.offset = value;
}
} /// <summary>
/// Birdate
/// </summary>
[DataMember]
public DateTime? BirdateStart
{
get
{
return this.birdateStart;
}
set
{
this.birdateStart = value;
}
} /// <summary>
/// Birdate
/// </summary>
[DataMember]
public DateTime? BirdateEnd
{
get
{
return this.birdateEnd;
}
set
{
this.birdateEnd = value;
}
} /// <summary>
/// Create Date Time
/// </summary>
[DataMember]
public DateTime? CreateDateTimeStart
{
get
{
return this.createDateTimeStart;
}
set
{
this.createDateTimeStart = value;
}
} /// <summary>
/// Create Date Time
/// </summary>
[DataMember]
public DateTime? CreateDateTimeEnd
{
get
{
return this.createDateTimeEnd;
}
set
{
this.createDateTimeEnd = value;
}
} /// <summary>
/// Update Date Time
/// </summary>
[DataMember]
public DateTime? UpdateDateTimeStart
{
get
{
return this.updateDateTimeStart;
}
set
{
this.updateDateTimeStart = value;
}
} /// <summary>
/// Update Date Time
/// </summary>
[DataMember]
public DateTime? UpdateDateTimeEnd
{
get
{
return this.updateDateTimeEnd;
}
set
{
this.updateDateTimeEnd = value;
}
} #endregion
}
}
ClientModel是数据基类,对应数据库表的字段 TableData.cs
/// <summary>
/// Table分页数据
/// </summary>
[Serializable]
[DataContract]
public class TableData
{
[DataMember]
public Int32 total { get; set; }
[DataMember]
public dynamic rows { get; set; }
}
GetClientList方法:
/// <summary>
/// 获取会员列表
/// </summary>
/// <returns></returns>
public Dictionary<Int32, List<ClientDomain>> GetClientList(ClientFilter filter)
{
Dictionary<Int32, List<ClientDomain>> list = null;
using (DBManager manager = this.GetDBManager())
{
list = dao.GetClientList(manager, filter);
}
return list;
}
通过dao.GetClientList方法获取分页数据,具体方法内容根据实际情况编写代码即可。