ExtJS Grid组件实现分页功能

在网上找了半天,也没有找到很好的Grid组件实现分页功能的实例。

用了半天时间搞定了,来记录下


前端使用的是ExtJS MVC模式

1. store

/// <reference path="../../../Ext/ext-all.js" />

Ext.define("AM.store.UserInfo", {
    extend: 'Ext.data.Store',
    model: 'AM.model.UserInfo',
    pageSize: 4,  //注意:这里表示的是每页的显示条数目
    proxy: {
        type: 'ajax',
        url: 'getPagedData.ashx', //请求后台的一般处理程序
        reader: {
            type: 'json',
            root: 'rows',
            //totalProperty: 'total', //注意:这里表示的是从后台返回的json数组中所获得的总条目数
        },
        writer: {
            type: 'json',
        },
    },
    //start代表的是要显示的页码上面的第一个条目在总条目中的index(也就是排第几个)
    //而limit就是每页要显示的条目数量
    autoLoad: { start: 0, limit: 4 },
    
});

store层要注意的就是注释的这几个配置项,具体内容看看API就清楚了


2. 看看API源码是怎么实现分页的

    getPageData : function(){
        var store = this.store,
            totalCount = store.getTotalCount();

        return {
            total : totalCount,
            currentPage : store.currentPage,
            pageCount: Math.ceil(totalCount / store.pageSize),
            fromRecord: ((store.currentPage - 1) * store.pageSize) + 1,
            toRecord: Math.min(store.currentPage * store.pageSize, totalCount)

        };
    },

store中的totalProperty代表的就是total
store.pageSize就是每页条目数
这样就算出来有多少页 pageCount
之后fromRecord,toRecord是通过条目在总条目中的index来确定起始和终止范围


3. view层添加paging分页组件

    dockedItems: [{
        xtype: 'pagingtoolbar',
        store: 'UserInfo',        
        dock: 'bottom',
        displayInfo: true,
        displayMsg: '显示{0}-{1}条,共{2}条',
        emptyMsg: '没有数据'
    }],

View层不涉及什么分页配置, 只是分页组件显示功能的配置


4. 后台实现(使用的是ASP.NET 一般处理程序 ashx)

Extjs向后台通过get method,传递start和limit两个参数,

后台获得这两个参数后,再根据实际情况计算出页码。比如:pageIndex = start/limit + 1 就是要显示的页码,

再根据pageIndex去数据库获取需要的数据,之后包装成json返回给store的url


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace IIPC.BookShop.Html
{
    public class BaseHandler:IHttpHandler
    {

        public bool IsReusable
        {
            get { return false; }
        }

        public HttpRequest Request { get; set; }
        public HttpResponse Response { get; set; }
        public virtual void ProcessRequest(HttpContext context)
        {
            Request = context.Request;
            Response = context.Response;
            Response.ContentType = "text/html";
        }
    }
}


using IIPC.BookShop.BLL;
using IIPC.BookShop.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace IIPC.BookShop.Html
{
    /// <summary>
    /// getPagedData 的摘要说明
    /// </summary>
    public class getPagedData : BaseHandler
    {

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            int startIndex = 0;
            int pageIndex = 1;
            int pageSize = 4;
            int pageCount;

            string limit = Request.QueryString["limit"];
            if (!int.TryParse(limit, out pageSize))
            {
                pageSize = 4;
            }

            string s = Request.QueryString["start"];
            if (!int.TryParse(s, out startIndex))
            {
                startIndex = 0;                
            }

            pageIndex = startIndex / pageSize + 1;

            UserInfoService userInfoService = new UserInfoService();
            List<UserInfo> list = userInfoService.GetPagedData(pageIndex, pageSize, out pageCount);            

            PagedData pd = new PagedData();
            pd.total = userInfoService.GetList().Count;
            pd.rows = list;
            Response.Write(JsonConvert.SerializeObject(pd));
        }

    }
}

pagedData类

    public class PagedData
    {
        public int total;
        public List<UserInfo> rows;
    }

最终返回json形式{"total":9,"rows":[{},{}...]}

其中total就是store层的totalProperty属性值,表示总条目数


5. DAL层实现取分页数据功能

        public List<UserInfo> GetPagedData(int pageIndex, int pageSize, out int pageCount)
        {
            SqlParameter[] ps = 
            {
                new SqlParameter("@pageIndex",SqlDbType.Int){Value = pageIndex},
                new SqlParameter("@pageSize",SqlDbType.Int){Value = pageSize},
                //输出参数
                new SqlParameter("@pageCount",SqlDbType.Int){Direction = ParameterDirection.Output}
            };
            List<UserInfo> list = new List<UserInfo>();
            DataTable dt = SqlHelper.ExecuteDataTableSP("[dbo].[usp_pagedUserInfo]", ps);
            pageCount = Convert.ToInt32(ps[2].Value);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    list.Add(RowToUserInfo(item));
                }
            }
            return list;
        }

这里pageCount并没有什么实际用途,可无视


6. 在数据库使用了存储过程进行分页数据的获取

USE [book_shop3]
GO
/****** Object:  StoredProcedure [dbo].[usp_pagedUserInfo]    Script Date: 2015/12/26 12:11:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[usp_pagedUserInfo]
	@pageIndex int,
	@pageSize int,
	@pageCount int output
as
begin
	declare @count int
			select @count = count(*) from UserInfo where IsDel = 0
			set @pageCount = ceiling(@count * 1.0 / @pageSize)
			select
				*
			from
				(SELECT *, row_number() OVER(ORDER BY Id DESC) AS num FROM UserInfo where IsDel = 0) AS t
			where
				num between (@pageIndex-1)*@pageSize+1 AND @pageIndex*@pageSize
				AND
				IsDel = 0
			order BY
				Id desc		
end

7. 小结

首先要注意每个配置参数写的位置,如store层包含proxy,proxy又包含reader

其次简单读一下源码可以厘清很多概念

最后觉得分层写代码思路更清晰


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值