asp.netMVC中实现分页方法

方法一:使用传统的sql语句实现分页,    public class UserprintDao如下

 
/// <summary>
        /// 取得用户申请记录列表(按分页)
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public List<Userprint> GetUserReportListByUserId(Userprint userprint)
        {
            string sql =
                "select * from (select row_number() over(order by id desc) as num,* from userprint where userid=@userid ";
            if (!string.IsNullOrEmpty(userprint.Printname))
            {
                sql += " and printname like @printname";
            }
            sql += ") as t where t.num>=@start and t.num<=@end";
            return DoUserprintList(sql, userprint);
        }

//统一函数返回打印列表
        public List<Userprint> DoUserprintList(string sql, Userprint userprint)
        {
            try
            {
                using (SqlConnection conn = SqlHelper.GetConn())
                {
                    return conn.Query<Userprint>(sql, userprint).ToList<Userprint>();
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        //统一函数返回记录总数
        public int DoRecordCount(string sql,Userprint userprint)
        {
            try
            {
                using (SqlConnection conn = SqlHelper.GetConn())
                {
                    return conn.ExecuteScalar(sql, userprint).ToString().ToInt32();
                }
            }
            catch (Exception)
            {
                return 0;
            } 
        }
/// <summary>
        /// 取用户申请记录列表总数
        /// </summary>
        /// <param name="userprint"></param>
        /// <returns></returns>
        public int GetUserReportRecordCount(Userprint userprint)
        {
            string sql = "select count(1) from userprint where userid=@userid";
            SqlParameter[] para;
            if (!string.IsNullOrEmpty(userprint.Printname))
            {
                sql += " and printname like @printname";
            }
            return DoRecordCount(sql, userprint);
        }

控制器中如下

 public ActionResult ReprotManage()
        {
             Userprint tempuserprint = new Userprint();
            var keys = Request["keys"];
            if (!string.IsNullOrEmpty(keys))
            {
                tempuserprint.Printname = "%"+keys+"%";
            }
           
            tempuserprint.Userid = getUserBySession().Id;
            int pageIndex = Request["pageIndex"] == null ? 1 : Request["pageIndex"].ToInt32();

            int pageCount = GetPageCount(tempuserprint, pageSize, printdao.GetUserReportRecordCount);

            int start = (pageIndex - 1) * pageSize + 1;
            int end = pageIndex * pageSize;
            tempuserprint.start = start;
            tempuserprint.end = end;

            ViewData.Model = printdao.GetUserReportListByUserId(tempuserprint);
            ViewBag.pageIndex = pageIndex;
            ViewBag.pageCount = pageCount;
            return View();
        }
        //计算分页总数,使用委托合成一个函数
        public int GetPageCount(Userprint userprint, int pageSize, Func<Userprint, int> GetRecordCount)
        {
            return Math.Ceiling((double)GetRecordCount(userprint) / pageSize).ToString().ToInt32();
        }

在view视图添加分页代码,代码如下:

 <div class="text-center">@Html.Raw(Print.PageBar.GetPageBarToUlLi(ViewBag.pageIndex, ViewBag.pageCount))</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;


namespace Print
{
    public class PageBar
    {
        public static string GetPageBarToUlLi(int pageIndex, int pageCount)
        {
            if (pageCount <= 1)
            {
                return string.Empty;
            }
            int start = pageIndex - 5;
            start = start < 1 ? 1 : start;
            int end = start + 9;
            end = end > pageCount ? pageCount : end;
            StringBuilder sb = new StringBuilder();
            sb.Append("<nav><ul class=‘pagination‘><li");
            if (pageIndex == 1)
                sb.Append(" class=‘disabled‘");
            sb.Append("><a href=‘?pageIndex=1‘ aria-label=‘Previous‘><span aria-hidden=‘true‘>").Append("第一页").Append("</span></a></li>");

            for (int i = start; i <= end; i++)
            {
                if (i == pageIndex)
                    sb.Append("<li class=‘active‘><a href=javascript:void(0)>" + i + "</a></li>");
                else
                {
                    sb.Append(string.Format("<li><a href=?pageIndex={0}>{0}</a></li>", i));
                }
            }
            sb.Append("<li");
            if (pageIndex == pageCount)
                sb.Append(" class=‘disabled‘");
            sb.Append("><a href=‘?pageIndex=").Append(pageCount).Append("‘ aria-label=‘Next‘> <span aria-hidden=‘true‘>最后一页</span></a></li></ul></nav>");
            return sb.ToString();
        }
        public static string GetPageBar(int pageIndex, int pageCount)
        {
            if (pageCount <= 1)
            {
                return string.Empty;
            }
            int start = pageIndex - 5;
            start = start < 1 ? 1 : start;
            int end = start + 9;
            end = end > pageCount ? pageCount : end;
            StringBuilder sb = new StringBuilder();
            sb.Append("<a href=?pageIndex=1>第一页</a>");
            for (int i = start; i <= end; i++)
            {
                if (i == pageIndex)
                    sb.Append(" " + i + " ");
                else
                {
                    sb.Append(string.Format("<a href=?pageIndex={0}>{0}</a>", i));
                }
            }
            sb.Append(string.Format("<a href=?pageIndex={0}>最后一页</a>", pageCount));
            return sb.ToString();
        }
    }
}

写的有点乱,这是从项目中复制出来的,其中使用到了ORM框架Dapper, js库jquery,UI美化:bootstrip,自行添加。

效果图如下:

技术分享

方法二:使用第三方库PageList,添加引用 ,使用NuGet添加:PagedList,同时也会添加PagedList.Mvc

在控制器中实现如下代码:

  public ActionResult Index(SearchInfo info, int page = 1){

   var result=(from p in db.userprints select p).OrderByDescending(m => m.addtime).ToPagedList(page, 17);
   if (Request.IsAjaxRequest())
           return PartialView("_statislist", statis);    
return View(result); }

在主视图中代码:

<div class="col-md-10">
            @Html.Partial("_statislist", Model)
        </div>

部分视图_statislist.cshtml代码如下:

@using PagedList.Mvc
@model IPagedList<Print.Entity.userprint>
          
<div id="statislist">
    <div class="pagedList" >
        @Html.PagedListPager(Model,page=>Url.Action("Index",new{page}),PagedListRenderOptions.Classic)
    </div>
    <table class="table table-hover table-striped">
        <tr>
            <th>
                文印名称
            </th>
            <th>
                打印色彩
            </th>
            <th>
                单双面
            </th>
          
            <th>
                纸张大小
            </th>
           
            
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.printname)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.printcolor)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.printmode)
                </td>
             
                <td>
                    @Html.DisplayFor(modelItem => item.printpagersize)
                </td>
               
            </tr>
        }
    </table>
</div>

为分页添加样式,此代码放在主视图就行

<script>
    $(function () {
       
        $(".pagedList a").click(function () {
            $.ajax({
                url: $(this).attr("href"),
                data: $("form").serialize(),
                type: "get"
            }).down(function (data) {
                $("#statislist").replaceWith(data);
            });
        });
    });
</script>

效果如下:

技术分享

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。