在上一篇博客《EasyUI 之 DataGrid的两种赋值方法》中,我们介绍了给DataGrid赋值的两种方法,同时我们也留下一个问题,分页效果没有真正的实现,今天我们就来给大家讲讲MVC+EasyUI-DataGrid怎么利用拉姆达表达式实现真分页查询。
首先,我们在DataGrid的URL中加上我们要查询的条件:查询用户名不是“呵呵”的所有用户。
<div>
<table id="dg" class="easyui-datagrid" style="width: 600px; height: 350px" >
<thead>
<tr>
<th data-options="field:'UserID',width:148,sortable:true">ID</th>
<th data-options="field:'UserName',width:148,sortable:true">姓名</th>
<th data-options="field:'Sex',width:148,sortable:true">性别</th>
</tr>
</thead>
</table>
</div>
<!--datagrid基本设置-->
<script type="text/javascript">
$(function () {
$('#dg').datagrid({
title: '测试表格',
url: "/EvaluationSituation/jsonTest?strUserName=呵呵", //添加查询条件
pagination: true,//显示分页工具栏
fitColumns: true, //自动大小
});
});
</script>
public JsonResult jsonTest()
{
#region 制造假数据
List<User> listUser = new List<User>();
listUser.Add(new User {
UserID ="001",
UserName="呵呵",
Sex ="男"
});
listUser.Add(new User
{
UserID = "002",
UserName = "哈哈",
Sex = "女"
});
listUser.Add(new User
{
UserID = "003",
UserName = "嘿嘿",
Sex = "男"
});
listUser.Add(new User
{
UserID = "004",
UserName = "嘻嘻",
Sex = "男"
});
listUser.Add(new User
{
UserID = "002",
UserName = "哈哈",
Sex = "女"
});
listUser.Add(new User
{
UserID = "003",
UserName = "嘿嘿",
Sex = "男"
});
listUser.Add(new User
{
UserID = "004",
UserName = "嘻嘻",
Sex = "男"
});
listUser.Add(new User
{
UserID = "002",
UserName = "哈哈",
Sex = "女"
});
listUser.Add(new User
{
UserID = "003",
UserName = "嘿嘿",
Sex = "男"
});
listUser.Add(new User
{
UserID = "004",
UserName = "嘻嘻",
Sex = "男"
});
listUser.Add(new User
{
UserID = "002",
UserName = "哈哈",
Sex = "女"
});
listUser.Add(new User
{
UserID = "003",
UserName = "嘿嘿",
Sex = "男"
});
listUser.Add(new User
{
UserID = "004",
UserName = "嘻嘻",
Sex = "男"
});
#endregion
string strUserName = Request["strUserName"];//查询条件
var pageIndex = int.Parse(Request["page"]);//当前页
var pageSize = int.Parse(Request["rows"]);//页面行数
var total = 0;
//首先得到符合该查询条件的总记录条数
total = listUser.Where(p => p.UserName != strUserName).Count();
//根据页号、页面大小和查询条件查询当前页应该显示的内容
var listQuery = listUser.Where(p => p.UserName != strUserName) //查询条件为:UserName不等于strUserName
.OrderBy(p => p.UserID) //根据UserID进行升序排序
.Skip(pageSize * (pageIndex - 1)) //跳过记录中的前(pageSize * (pageIndex - 1))行,假如当前页为第二页-pageIndex=2,每页显示10条数据-pageSize=10,那么就跳过记录中的前10条数据,达到分页查询的效果
.Take(pageSize); //取出pageSize条记录
var data = new
{
total,
rows = listQuery
};
//将数据转换成Json格式
JsonResult jsonUser = new JsonResult();
jsonUser = Json(data);
return jsonUser;
}
然后我们就可以看见结果:
分页查询是一个很普通的东西,基本上只要有表格就需要分页查询,所以这些东西我们还是需要掌握。其中的拉姆达表达式,我们也可以在VS中通过F12转到定义,多看看其中方法的定义。