构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(8)-MVC与EasyUI DataGrid 分页

前言

为了符合后面更新后的重构系统,文章于2016-11-1日重写 EasyUI Datagrid在加载的时候会提交一些分页的信息到后台,我们需要根据这些信息来进行数据分页再次返回到前台

实现

首先要让DataGrid支持分页,我们需要在JS Datagrid中加入下列几个属性

  1. 是否启用分页:pagination 默认是false
  2. 每页数量:pageSize 默认10
  3. 可选择每页数量:pageList 默认[10,20,30,40,50]
  4. 排序字段:sortName 默认null
  5. 排序类型:sortOrder 默认asc

OK加入后的代码变成这样

  $(function () {
        $('#List').datagrid({
            url: '/SysSample/GetList',
            width: $(window).width() - 10,
            methord: 'post',
            height: $(window).height() - 35,
            fitColumns: true,
            sortName: 'Id',
            sortOrder: 'desc',
            idField: 'Id',
            pageSize: 15,
            pageList: [15, 20, 30, 40, 50],
            pagination: true,
            striped: true, //奇偶行是否区分
            singleSelect: true,//单选模式
            rownumbers: true,//行号
            columns: [[
                { field: 'Id', title: 'ID', width: 80 },
                { field: 'Name', title: '名称', width: 120 },
                { field: 'Age', title: '年龄', width: 80, align: 'right' },
                { field: 'Bir', title: '生日', width: 80, align: 'right' },
                { field: 'Photo', title: '照片', width: 250 },
                { field: 'Note', title: '说明', width: 60, align: 'center' },
                { field: 'CreateTime', title: '创建时间', width: 60, align: 'center' }
            ]]
        });
    });

预览一下

实际已经分页,但是不正确的,每一页的数据一样。我们要根据分页的参数去取

查看技巧

OK我们控制器要根据他传递的参数写同样的参数名称,否则获取不到

看我们的SysSampleController 下的GetList方法,加入参数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.BLL;
using App.IBLL;
using App.Models;
using App.Models.Sys;
using Microsoft.Practices.Unity;

namespace App.Admin.Controllers
{
    public class SysSampleController : Controller
    {
        //
        // GET: /SysSample/
        /// <summary>
        /// 业务层注入
        /// </summary>
        [Dependency]
        public ISysSampleBLL m_BLL { get; set; }
        public ActionResult Index()
        {
            
            return View();
        }
        [HttpPost]
        public JsonResult GetList(int page = 1, int rows = 10, string sort = "Id", string order = "desc")
        {
            int total = 0;
            List<SysSampleModel> list = m_BLL.GetList(page, rows, sort, order, ref total);
            var json = new
            {
                total = total,
                rows = (from r in list
                        select new SysSampleModel()
                        {

                            Id = r.Id,
                            Name = r.Name,
                            Age = r.Age,
                            Bir = r.Bir,
                            Photo = r.Photo,
                            Note = r.Note,
                            CreateTime = r.CreateTime,

                        }).ToArray()
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }
    }
}

BLL代码修改(IBLL也要修改参数 List<SysSampleModel> GetList(int page, int rows, string sort, string order,ref int total);)

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;
using App.Models;
using App.Common;
using App.Models.Sys;
using App.IBLL;
using App.IDAL;


namespace App.BLL
{
    public class SysSampleBLL : ISysSampleBLL
    {
        DBContainer db = new DBContainer();
        [Dependency]
        public ISysSampleRepository Rep { get; set; }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="pager">JQgrid分页</param>
        /// <param name="queryStr">搜索条件</param>
        /// <returns>列表</returns>
        public List<SysSampleModel> GetList(int page, int rows, string sort, string order, ref int total)
        {
            IQueryable<SysSample> queryData = null;
            queryData = Rep.GetList(db);
            
            //排序
            if (order == "desc")
            {
                switch (order)
                {
                    case "Id":
                        queryData = queryData.OrderByDescending(c => c.Id);
                        break;
                    case "Name":
                        queryData = queryData.OrderByDescending(c => c.Name);
                        break;
                    default:
                        queryData = queryData.OrderByDescending(c => c.CreateTime);
                        break;
                }
            }
            else
            {

                switch (order)
                {
                    case "Id":
                        queryData = queryData.OrderBy(c => c.Id);
                        break;
                    case "Name":
                        queryData = queryData.OrderBy(c => c.Name);
                        break;
                    default:
                        queryData = queryData.OrderBy(c => c.CreateTime);
                        break;
                }
            }
            return CreateModelList(ref queryData,page,rows,ref total);
        }


        private List<SysSampleModel> CreateModelList(ref IQueryable<SysSample> queryData,int page,int rows,ref int total)
        {

            total = queryData.Count();
            if (total > 0)
            {
                if (page <= 1)
                {
                    queryData = queryData.Take(rows);
                }
                else
                {
                    queryData = queryData.Skip((page - 1) * rows).Take(rows);
                }
            }
            List<SysSampleModel> modelList = (from r in queryData
                                              select new SysSampleModel
                                              {
                                                  Id = r.Id,
                                                  Name = r.Name,
                                                  Age = r.Age,
                                                  Bir = r.Bir,
                                                  Photo = r.Photo,
                                                  Note = r.Note,
                                                  CreateTime = r.CreateTime,

                                              }).ToList();

            return modelList;
        }

        /// <summary>
        /// 创建一个实体
        /// </summary>
        /// <param name="errors">持久的错误信息</param>
        /// <param name="model">模型</param>
        /// <returns>是否成功</returns>
        public bool Create( SysSampleModel model)
        {
            try
            {
                SysSample entity = Rep.GetById(model.Id);
                if (entity != null)
                {
                    return false;
                }
                entity = new SysSample();
                entity.Id = model.Id;
                entity.Name = model.Name;
                entity.Age = model.Age;
                entity.Bir = model.Bir;
                entity.Photo = model.Photo;
                entity.Note = model.Note;
                entity.CreateTime = model.CreateTime;

                if (Rep.Create(entity) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                //ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 删除一个实体
        /// </summary>
        /// <param name="errors">持久的错误信息</param>
        /// <param name="id">id</param>
        /// <returns>是否成功</returns>
        public bool Delete(string id)
        {
            try
            {
                if (Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
   
        /// <summary>
        /// 修改一个实体
        /// </summary>
        /// <param name="errors">持久的错误信息</param>
        /// <param name="model">模型</param>
        /// <returns>是否成功</returns>
        public bool Edit(SysSampleModel model)
        {
            try
            {
                SysSample entity = Rep.GetById(model.Id);
                if (entity == null)
                {
                    return false;
                }
                entity.Name = model.Name;
                entity.Age = model.Age;
                entity.Bir = model.Bir;
                entity.Photo = model.Photo;
                entity.Note = model.Note;


                if (Rep.Edit(entity) == 1)
                {
                    return true;
                }
                else
                {

                    return false;
                }

            }
            catch (Exception ex)
            {

                //ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 判断是否存在实体
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns>是否存在</returns>
        public bool IsExists(string id)
        {
            if (db.SysSample.SingleOrDefault(a => a.Id == id) != null)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 根据ID获得一个实体
        /// </summary>
        /// <param name="id">id</param>
        /// <returns>实体</returns>
        public SysSampleModel GetById(string id)
        {
            if (IsExist(id))
            {
                SysSample entity = Rep.GetById(id);
                SysSampleModel model = new SysSampleModel();
                model.Id = entity.Id;
                model.Name = entity.Name;
                model.Age = entity.Age;
                model.Bir = entity.Bir;
                model.Photo = entity.Photo;
                model.Note = entity.Note;
                model.CreateTime = entity.CreateTime;

                return model;
            }
            else
            {
                return new SysSampleModel();
            }
        }

        /// <summary>
        /// 判断一个实体是否存在
        /// </summary>
        /// <param name="id">id</param>
        /// <returns>是否存在 true or false</returns>
        public bool IsExist(string id)
        {
            return Rep.IsExist(id);
        }
    }
}

 我们要在BLL层返回当前查询的全部条数,还要返回当前页得数据

补脑:ref关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用ref参数,则方法定义和调用方法都必须显式使用ref关键字。 大家看出这样太麻烦了,代码太不漂亮了,我们把常用的参数给封装了。

分装分页

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace App.Common
{
     public class GridPager
    {
 
      
         public int rows { get; set; }//每页行数
         public int page { get; set; }//当前页是第几页
         public string order { get; set; }//排序方式
         public string sord { get; set; }//排序列
         public int totalRows { get; set; }//总行数

         public int totalPages //总页数
         {
             get
             {
                 return (int)Math.Ceiling((float)totalRows / (float)rows);
             }
         }
    }
}

把这个类放到Apps.Common, 我们的Apps.Common终于用到了 再次修改Controller的GetList

   [HttpPost]
        public JsonResult GetList(GridPager pager)
        {
            List<SysSampleModel> list = m_BLL.GetList(ref pager);
            var json = new
            {
                total = pager.totalRows,
                rows = (from r in list
                        select new SysSampleModel()
                        {

                            Id = r.Id,
                            Name = r.Name,
                            Age = r.Age,
                            Bir = r.Bir,
                            Photo = r.Photo,
                            Note = r.Note,
                            CreateTime = r.CreateTime,

                        }).ToArray()

            };

            return Json(json, JsonRequestBehavior.AllowGet);
        }

和修改BLL的GetList 还要修改IBLL --List<SysSampleModel> GetList(ref GridPager pager);

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;
using App.Models;
using App.Common;
using App.Models.Sys;
using App.IBLL;
using App.IDAL;


namespace App.BLL
{
    public class SysSampleBLL : ISysSampleBLL
    {
        DBContainer db = new DBContainer();
        [Dependency]
        public ISysSampleRepository Rep { get; set; }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="pager">JQgrid分页</param>
        /// <param name="queryStr">搜索条件</param>
        /// <returns>列表</returns>
        public List<SysSampleModel> GetList(ref GridPager pager)
        {

            IQueryable<SysSample> queryData = null;
          
                queryData = Rep.GetList(db);

            //排序
            if (pager.order == "desc")
            {
                switch (pager.order)
                {
                    case "CreateTime":
                        queryData = queryData.OrderByDescending(c => c.CreateTime);
                        break;
                    case "Name":
                        queryData = queryData.OrderByDescending(c => c.Name);
                        break;
                    default:
                        queryData = queryData.OrderByDescending(c => c.CreateTime);
                        break;
                }
            }
            else
            {

                switch (pager.order)
                {
                    case "CreateTime":
                        queryData = queryData.OrderBy(c => c.CreateTime);
                        break;
                    case "Name":
                        queryData = queryData.OrderBy(c => c.Name);
                        break;
                    default:
                        queryData = queryData.OrderBy(c => c.CreateTime);
                        break;
                }
            }
            return CreateModelList(ref pager, ref queryData);
        }
        private List<SysSampleModel> CreateModelList(ref GridPager pager, ref IQueryable<SysSample> queryData)
        {

            pager.totalRows = queryData.Count();
            if (pager.totalRows > 0)
            {
                if (pager.page <= 1)
                {
                    queryData = queryData.Take(pager.rows);
                }
                else
                {
                    queryData = queryData.Skip((pager.page - 1) * pager.rows).Take(pager.rows);
                }
            }
            List<SysSampleModel> modelList = (from r in queryData
                                              select new SysSampleModel
                                              {
                                                  Id = r.Id,
                                                  Name = r.Name,
                                                  Age = r.Age,
                                                  Bir = r.Bir,
                                                  Photo = r.Photo,
                                                  Note = r.Note,
                                                  CreateTime = r.CreateTime,

                                              }).ToList();

            return modelList;
        }

        /// <summary>
        /// 创建一个实体
        /// </summary>
        /// <param name="errors">持久的错误信息</param>
        /// <param name="model">模型</param>
        /// <returns>是否成功</returns>
        public bool Create( SysSampleModel model)
        {
            try
            {
                SysSample entity = Rep.GetById(model.Id);
                if (entity != null)
                {
                    return false;
                }
                entity = new SysSample();
                entity.Id = model.Id;
                entity.Name = model.Name;
                entity.Age = model.Age;
                entity.Bir = model.Bir;
                entity.Photo = model.Photo;
                entity.Note = model.Note;
                entity.CreateTime = model.CreateTime;

                if (Rep.Create(entity) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                //ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 删除一个实体
        /// </summary>
        /// <param name="errors">持久的错误信息</param>
        /// <param name="id">id</param>
        /// <returns>是否成功</returns>
        public bool Delete(string id)
        {
            try
            {
                if (Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
   
        /// <summary>
        /// 修改一个实体
        /// </summary>
        /// <param name="errors">持久的错误信息</param>
        /// <param name="model">模型</param>
        /// <returns>是否成功</returns>
        public bool Edit(SysSampleModel model)
        {
            try
            {
                SysSample entity = Rep.GetById(model.Id);
                if (entity == null)
                {
                    return false;
                }
                entity.Name = model.Name;
                entity.Age = model.Age;
                entity.Bir = model.Bir;
                entity.Photo = model.Photo;
                entity.Note = model.Note;


                if (Rep.Edit(entity) == 1)
                {
                    return true;
                }
                else
                {

                    return false;
                }

            }
            catch (Exception ex)
            {

                //ExceptionHander.WriteException(ex);
                return false;
            }
        }
        /// <summary>
        /// 判断是否存在实体
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns>是否存在</returns>
        public bool IsExists(string id)
        {
            if (db.SysSample.SingleOrDefault(a => a.Id == id) != null)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 根据ID获得一个实体
        /// </summary>
        /// <param name="id">id</param>
        /// <returns>实体</returns>
        public SysSampleModel GetById(string id)
        {
            if (IsExist(id))
            {
                SysSample entity = Rep.GetById(id);
                SysSampleModel model = new SysSampleModel();
                model.Id = entity.Id;
                model.Name = entity.Name;
                model.Age = entity.Age;
                model.Bir = entity.Bir;
                model.Photo = entity.Photo;
                model.Note = entity.Note;
                model.CreateTime = entity.CreateTime;

                return model;
            }
            else
            {
                return new SysSampleModel();
            }
        }

        /// <summary>
        /// 判断一个实体是否存在
        /// </summary>
        /// <param name="id">id</param>
        /// <returns>是否存在 true or false</returns>
        public bool IsExist(string id)
        {
            return Rep.IsExist(id);
        }
    }
}

代码漂亮了不少,预览一下,还是正确的效果了。

总结

文章中一直演示做法,这种方式看起来非常反感,但是都是为了更好更仔细的了解系统,为后面快速开发做铺垫

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏大内老A

谈谈WCF中的Data Contract(4):WCF Data Contract Versioning

软件工程是一门独特的工程艺术,需要解决的是不断改变的需求变化。而对于WCF,对于SOA,由于涉及的是对多个系统之间的交互问题,如何有效地解决不断改变的需求所带来...

26050
来自专栏游戏杂谈

Unity项目中文字的统一管理

一款游戏在研发初期就需要考虑多语言的问题,否则后期在进行多国语言版本时就面临着巨大的成本。鉴于之前页游的经验,其它同事设计出读取Excel的方式来管理所有的文字...

14910
来自专栏along的开发之旅

C#操作注册表,设置系统环境变量

最近重装系统,NX9.0太大了,不想重装,原来的话重装LicenceServer后,NX9.0是可以直接打开的,但是.NET二次开发的时候有错误,这次试一下添...

10030
来自专栏菩提树下的杨过

ExtJs学习笔记(5)_Ajax示例

ExtJs对于Ajax的使用非常简单,看下面的代码: 1.Html页: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0...

22760
来自专栏张高兴的博客

张高兴的 Windows 10 IoT 开发笔记:串口红外编解码模块 YS-IRTM

This is a Windows 10 IoT Core project on the Raspberry Pi 2/3, coded by C#.

20520
来自专栏飞扬的花生

Html5上传插件封装

      前段时间将flash的上传控件替换成使用纯js实现的,在此记录 1.创建标签 <div class="camera-area" style="dis...

43280
来自专栏hbbliyong

C# ini文件读写类

VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面是一个C# ini文件读写类, 从网上收集的,很全,就是没有对...

35460
来自专栏ASP.NET MVC5 后台权限管理系统

ASP.NET MVC5+EF6+EasyUI 后台管理系统(58)-DAL层重构

前言:这是对本文系统一次重要的革新,很久就想要重构数据访问层了,数据访问层重复代码太多。主要集中增删该查每个模块都有,所以本次是为封装相同接口方法    如果你...

34360
来自专栏用户画像

通过 HttpClient 从指定服务器获取数据

29220
来自专栏大内老A

我的WCF之旅(13):创建基于MSMQ的Responsive Service

一、One-way MEP V.S. Responsible Service 我们知道MSMQ天生就具有异步的特性,它只能以One-way的MEP(Messag...

23260

扫码关注云+社区

领取腾讯云代金券