http://www.cnblogs.com/coolcode/archive/2009/05/24/1488353.html
看了这位兄弟的分页源码,但还是没看懂咋调用,知道他是扩展了一个helper分页方法,但在Controller层中如何处理页码,页显示记录数,和总记录数?在这方面(mvc)是菜鸟,谢谢请教!/// <summary>  
        /// 分页Pager显示  
        /// </summary>   
        /// <param name="html"></param>  
        /// <param name="currentPageStr">标识当前页码的QueryStringKey</param>   
        /// <param name="pageSize">每页显示</param>  
        /// <param name="totalCount">总数据量</param>  
        /// <returns></returns> 
        public static string Pager(this HtmlHelper html, string currentPageStr, int pageSize, int totalCount)
        {
            var queryString = html.ViewContext.HttpContext.Request.QueryString;
            int currentPage = 1; //当前页  
            var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数  
            var dict = new System.Web.Routing.RouteValueDictionary(html.ViewContext.RouteData.Values);
            var output = new System.Text.StringBuilder();
            if (!string.IsNullOrEmpty(queryString[currentPageStr]))
            {
                //与相应的QueryString绑定 
                foreach (string key in queryString.Keys)
                    if (queryString[key] != null && !string.IsNullOrEmpty(key))
                        dict[key] = queryString[key];
                int.TryParse(queryString[currentPageStr], out currentPage);
            }
            else
            {
                //获取 ~/Page/{page number} 的页号参数
                 int .TryParse(dict[currentPageStr].ToString(), out currentPage );
            }
            if (currentPage <= 0) currentPage = 1;
            if (totalPages > 1)
            {
                if (currentPage != 1)
                {
                    //处理首页连接  
                    dict[currentPageStr] = 1;
                    output.AppendFormat("{0} ", html.RouteLink("首页", dict));
                }
                if (currentPage > 1)
                {
                    //处理上一页的连接  
                    dict[currentPageStr] = currentPage - 1;
                    output.Append(html.RouteLink("上一页", dict));
                }
                else
                {
                    output.Append("上一页");
                }
                output.Append(" ");
                int currint = 5;
                for (int i = 0; i <= 10; i++)
                {
                    //一共最多显示10个页码,前面5个,后面5个  
                    if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
                        if (currint == i)
                        {
                            //当前页处理  
                            output.Append(string.Format("[{0}]", currentPage));
                        }
                        else
                        {
                            //一般页处理 
                            dict[currentPageStr] = currentPage + i - currint;
                            output.Append(html.RouteLink((currentPage + i - currint).ToString(), dict));
                        }
                    output.Append(" ");
                }
                if (currentPage < totalPages)
                {
                    //处理下一页的链接 
                    dict[currentPageStr] = currentPage + 1;
                    output.Append(html.RouteLink("下一页", dict));
                }
                else
                {
                    output.Append("下一页");
                }
                output.Append(" ");
                if (currentPage != totalPages)
                {
                    dict[currentPageStr] = totalPages;
                    output.Append(html.RouteLink("末页", dict));
                }
                output.Append(" ");
            }
            output.AppendFormat("{0} / {1}", currentPage, totalPages);//这个统计加不加都行 
            return output.ToString();
        }

解决方案 »

  1.   

    页面调用的时候,在aspx里写
    <%=HTML.Pager(“这个就是页码参数名字”, 每页条数,比如10, 总共多少条数据,比如1000) >
      

  2.   

    LZ看下这个分页, 也是我在网上找到的,感觉效率还不错。
    前台  <asp:datalist id="datalist1" AlternatingItemStyle-BackColor="#f3f3f3" Width="100%" CellSpacing="0" CellPadding="0" Runat="server"> 
    <ItemTemplate> 
    <table width="100%" border="0" cellspacing="0" cellpadding="0"> 
    <tr> 
    <td width="30%" align="center"><%#DataBinder.Eval(Container.DataItem,"name")%></td> 
    <td width="30%" align="center"><%#DataBinder.Eval(Container.DataItem,"age")%></td> 
    <td width="30%" align="center"><%#DataBinder.Eval(Container.DataItem,"id")%></td> 
    </tr> 
    </table> 
    </ItemTemplate> 
    </asp:datalist>  &nbsp;<div align="center">共<asp:label id="LPageCount" Runat="server" ForeColor="#ff0000"></asp:label>页/共 
    <asp:label id="LRecordCount" Runat="server" ForeColor="#ff0000"></asp:label>记录 
    <asp:linkbutton id="Fistpage" Runat="server" CommandName="0">首页</asp:linkbutton> 
    <asp:linkbutton id="Prevpage" Runat="server" CommandName="prev">上一页</asp:linkbutton> 
    <asp:linkbutton id="Nextpage" Runat="server" CommandName="next">下一页</asp:linkbutton> 
    <asp:linkbutton id="Lastpage" Runat="server" CommandName="last">尾页</asp:linkbutton> 
    当前第<asp:label id="LCurrentPage" Runat="server" ForeColor="#ff0000"></asp:label>页 
    跳页<asp:TextBox ID="gotoPage" Runat="server" Width="30px" MaxLength="5" AutoPostBack="True"></asp:TextBox> 
    </div> 
    后台
       //定义每页显示记录
            const int PageSize = 20;
            //定义几个保存分页参数变量
            int PageCount, RecCount, CurrentPage, Pages, JumpPage;
            private void Page_Load(object sender, System.EventArgs e)
            {
                if (!IsPostBack)
                {
                    //通过Calc()函数获取总记录数
                    RecCount = Calc();
                    //计算总页数(加上OverPage()函数防止有余数造成显示数据不完整)
                    PageCount = RecCount / PageSize + OverPage();
                    //保存总页参数到ViewState(减去ModPage()函数防止SQL语句执行时溢出查询范围,可以用存储过程分页算法来理解这句)
                    ViewState["PageCounts"] = RecCount / PageSize - ModPage();
                    //保存一个为0的页面索引值到ViewState
                    ViewState["PageIndex"] = 0;
                    //保存PageCount到ViewState,跳页时判断用户输入数是否超出页码范围
                    ViewState["JumpPages"] = PageCount;
                    //显示LPageCount、LRecordCount的状态
                    LPageCount.Text = PageCount.ToString();
                    LRecordCount.Text = RecCount.ToString();
                    //判断跳页文本框失效
                    if (RecCount <= 20)
                    {
                        gotoPage.Enabled = false;
                    }
                    //调用数据绑定函数TDataBind()进行数据绑定运算
                    TDataBind();
                }
            }
            //计算余页
            public int OverPage()
            {
                int pages = 0;
                if (RecCount % PageSize != 0)
                    pages = 1;
                else
                    pages = 0;
                return pages;
            }
            //计算余页,防止SQL语句执行时溢出查询范围
            public int ModPage()
            {
                int pages = 0;
                if (RecCount % PageSize == 0 && RecCount != 0)
                    pages = 1;
                else
                    pages = 0;
                return pages;
            }
            // 计算总记录的静态函数
            // 本人在这里使用静态函数的理由是:如果引用的是静态数据或静态函数,
            // 连接器会优化生成代码,去掉动态重定位项(对海量数据表分页效果更明显)。
            // 希望大家给予意见、如有不正确的地方望指正。
            public static int Calc()
            {
                int RecordCount = 0;
                SqlCommand MyCmd = new SqlCommand("select count(*) as co from fenye", MyCon());
                SqlDataReader dr = MyCmd.ExecuteReader();
                if (dr.Read())
                    RecordCount = Int32.Parse(dr["co"].ToString());
                MyCmd.Connection.Close();
                return RecordCount;
            }
            //数据库连接语句(从Web.Config中获取)
            public static SqlConnection MyCon()
            {
                SqlConnection MyConnection = new SqlConnection("server=.;uid=sa;pwd=sasa;database=NorthWind");
                MyConnection.Open();
                return MyConnection;
            }
            //对四个按钮(首页、上一页、下一页、尾页)返回的CommandName值进行操作
            private void Page_OnClick(object sender, CommandEventArgs e)
            {
                //从ViewState中读取页码值保存到CurrentPage变量中进行参数运算
                CurrentPage = (int)ViewState["PageIndex"];
                //从ViewState中读取总页参数运算
                Pages = (int)ViewState["PageCounts"];
                string cmd = e.CommandName;
                //筛选CommandName
                switch (cmd)
                {
                    case "next":
                        CurrentPage++;
                        break;
                    case "prev":
                        CurrentPage--;
                        break;
                    case "last":
                        CurrentPage = Pages;
                        break;
                    default:
                        CurrentPage = 0;
                        break;
                }
                //将运算后的CurrentPage变量再次保存至ViewState
                ViewState["PageIndex"] = CurrentPage;
                //调用数据绑定函数TDataBind()
                TDataBind();
            }
            private void TDataBind()
            {
                //从ViewState中读取页码值保存到CurrentPage变量中进行按钮失效运算
                CurrentPage = (int)ViewState["PageIndex"];
                //从ViewState中读取总页参数进行按钮失效运算
                Pages = (int)ViewState["PageCounts"];
                //判断四个按钮(首页、上一页、下一页、尾页)状态
                if (CurrentPage + 1 > 1)
                {
                    Fistpage.Enabled = true;
                    Prevpage.Enabled = true;
                }
                else
                {
                    Fistpage.Enabled = false;
                    Prevpage.Enabled = false;
                }
                if (CurrentPage == Pages)
                {
                    Nextpage.Enabled = false;
                    Lastpage.Enabled = false;
                }
                else
                {
                    Nextpage.Enabled = true;
                    Lastpage.Enabled = true;
                }
                //数据绑定到DataList控件
                DataSet ds = new DataSet();
                //核心SQL语句,进行查询运算(决定了分页的效率:))
                SqlDataAdapter MyAdapter = new SqlDataAdapter("Select Top " + PageSize + " * from fenye where id not in(select top " + PageSize * CurrentPage + " id from fenye order by id desc) order by id desc", MyCon());
                MyAdapter.Fill(ds, "news");
                datalist1.DataSource = ds.Tables["news"].DefaultView;
                datalist1.DataBind();
                //显示Label控件LCurrentPaget和文本框控件gotoPage状态
                LCurrentPage.Text = (CurrentPage + 1).ToString();
                gotoPage.Text = (CurrentPage + 1).ToString();
                //释放SqlDataAdapter
                MyAdapter.Dispose();
            }
            #region Web 窗体设计器生成的代码
            override protected void OnInit(EventArgs e)
            {
                //
                // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
                //
                InitializeComponent();
                base.OnInit(e);
            }
            /// <summary>
            /// 设计器支持所需的方法 - 不要使用代码编辑器修改
            /// 此方法的内容。
            /// </summary>
            private void InitializeComponent()
            {
                this.Fistpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
                this.Prevpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
                this.Nextpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
                this.Lastpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
                this.gotoPage.TextChanged += new System.EventHandler(this.gotoPage_TextChanged);
                this.Load += new System.EventHandler(this.Page_Load);
            }
            #endregion
            //跳页代码
            private void gotoPage_TextChanged(object sender, System.EventArgs e)
            {
                try
                {
                    //从ViewState中读取可用页数值保存到JumpPage变量中
                    JumpPage = (int)ViewState["JumpPages"];
                    //判断用户输入值是否超过可用页数范围值
                    if (Int32.Parse(gotoPage.Text) > JumpPage || Int32.Parse(gotoPage.Text) <= 0)
                    {
                        Response.Write("<script>alert('页码范围越界!');location.href='WebForm8.aspx'</script>");
                    }
                    else
                    {
                        //转换用户输入值保存在int型InputPage变量中
                        int InputPage = Int32.Parse(gotoPage.Text.ToString()) - 1;
                        //写入InputPage值到ViewState["PageIndex"]中
                        ViewState["PageIndex"] = InputPage;
                        //调用数据绑定函数TDataBind()再次进行数据绑定运算
                        TDataBind();
                    }
                }
                //捕获由用户输入不正确数据类型时造成的异常
                catch (Exception eXP)
                {
                    Response.Write("<script>alert(' + exp.Message + ');location.href='WebForm8.aspx'</script>");
                }
            }
      

  3.   

    boylee83兄
    关键我在 Controller层不知咋处理它呀
    public ActionResult Index()
            {
                ProductBLL Bl = new ProductBLL();
                List<MVCSolution.Models.ProductModel> l = Bl.GetList();
                return View("Index", l);
            }
      

  4.   

    liuxibei1987兄,我要的是asp.net mvc的分页处理方法
      

  5.   

    http://blog.csdn.net/chsword/archive/2009/05/11/4166564.aspx 
    重典兄也有一个方案 但没有提供源码
      

  6.   


    关键我在 Controller层不知咋处理它呀 
    public ActionResult Index() 
            { 
                ProductBLL Bl = new ProductBLL(); 
                List <MVCSolution.Models.ProductModel> l = Bl.GetList(); 
                return View("Index", l); 
            }
     我感觉在这里 加上页码的参数传给view就可以了
    Global.asax:
        routes.MapRoute(
                    "Default",                                              // Route name
                    "{controller}/{action}/{pageIndex}",                           // URL with parameters
                    new { controller = "controllerName", action = "Index", pageIndex= "" }  // Parameter defaultspublic ActionResult Index(string pageIndex) 
            {
              ProductBLL Bl = new ProductBLL(); 
                List <MVCSolution.Models.ProductModel> l = Bl.GetList(); 
                 ViewData["pageIndex"] = pageIndex;
                //这里应该根据页码,以及预定义的分页数据量n,获取当前页的数据,具体自己实现了               List <MVCSolution.Models.ProductModel> subL = getCurrentPageData(l,n,pageIndex);            return View("Index", subL); 
      

  7.   

    http://blog.csdn.net/chsword/archive/2009/05/11/4166564.aspx 
    有谁能看懂重典兄的分页思路吗,给个实例源码
      

  8.   

    感觉圈内了解asp.net mvc 的人还是比较少
      

  9.   

    欢迎各位加入ASP.NET MVC框架超级群!让我们共同学习、进步!QQ群号:40985466 非常乐意为大家提供一个良好的交流平台!
      

  10.   

    试试MvcPager: http://www.webdiyer.com/Products/MvcPager/
      

  11.   

    http://download.csdn.net/detail/kingson88/3547016
      

  12.   

    http://download.csdn.net/detail/kingson88/3547016