EF 利用PagedList進行分頁並結合查詢 方法2

微軟提供了PagedList分頁,相信你們在網上也能搜索一大堆關於pagedList用法的博客,論壇。可是,在使用的過程當中一不當心,就會掉入pagedList某種常規用法的陷阱。css

我所說的某種常規用法是指以下方法(也能夠參考個人博客:PagedList 分頁用法):html

代碼以下:前端

複製代碼
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Linq;
using EF_Test.DAL;
using System.Data;
using PagedList;

namespace EF_Test.Controllers
{
    public class HomeController : Controller
    {
        private StudentContext db = new StudentContext();
        /// <summary>
        /// 簡單分頁演示
        /// </summary>
        /// <param name="page">頁碼</param>
        /// <returns></returns>
        public ActionResult Index2(int page = 1)//查詢全部學生數據
        {
            return View(db.Students.OrderBy(item => item.Id).ToPagedList(page, 9));
        }
    }
}
複製代碼

前端HTMLsql

複製代碼
@model PagedList.IPagedList<EF_Test.DAL.Student>
@using PagedList.Mvc
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section css{
    <link href="~/Content/PagedList.css" rel="stylesheet" />
    <style type="text/css">
        body {
            font-size: 12px;
            font-family: "微軟雅黑";
            color: #555;
            position: relative;
            background: #fff;
        }

        a {
            text-decoration: none;
            color: #555;
        }

        #tbList {
            border: 1px solid none;
            width: 800px;
            margin: 10px auto;
            border-collapse: collapse;
        }

            #tbList th, td {
                border: 1px solid #ccc;
                padding: 5px;
                text-align: center;
            }

        tfoot tr td {
            border: none;
        }
    </style>
}

@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
    <div style="text-align: center;">
        <h1>Mvc分頁例子</h1>
        <table id="tbList">

           
            <tbody>
                @if (Model.Count() != 0)
                {  
                    <tr>
                        <th>姓名
                        </th>
                        <th>性別
                        </th>
                        <th>學號
                        </th>
                    </tr>
                    foreach (var item in Model)
                    {   
                    <tr style="text-align: center;">
                        <td>
                            @Html.DisplayFor(modelItem => item.Name)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Sex)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.StudentNum)
                        </td>
                    </tr>  
                    }

                }
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="5">
                        <div class="">
                            @if (Model != null)
                            {  
                                <span style="height: 20px; line-height: 20px;">共 @Model.TotalItemCount.ToString() 條記錄,當前第 @Model.PageNumber 頁/共 @Model.PageCount 頁 </span>  
                                @Html.PagedListPager(Model, page => Url.Action("Index", new { page }), new PagedListRenderOptions() { LinkToFirstPageFormat = "首頁", LinkToNextPageFormat = "下一頁", LinkToPreviousPageFormat = "上一頁", LinkToLastPageFormat = "末頁", DisplayItemSliceAndTotal = false, MaximumPageNumbersToDisplay = 3 })    
                            }
                        </div>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
}
複製代碼

上述的用法很簡單,直接查詢全部數據,而後利用pagedList提供的HTML helper 進行分頁。後端

其效果圖也不錯,以下:ide

上述中紅色字體提到:該用法須要一次性查詢表中全部數據,試問:若是您的數據表中有百萬甚至千萬條數據,那麼這種用法效率是否是將會很低?字體

說來也慚愧,當初用的時候,我也想到了這個弊端,可是一直沒去想辦法解決這個問題。spa

還好,pagedList還提供了另一種方法:StaticPagedList 方法3d

StaticPagedList 方法須要提供四個參數,分別爲:數據源  當前頁碼  每頁條數  以及總記錄數code

如上述所言,咱們在查詢的過程當中不能一次性查詢全部數據,由於這樣作效率很低。而如今咱們要作的就是查詢當前頁碼的 10 條數據(假設每頁展現十條數據)及返回數據表中的總記錄數。

那麼咱們該怎麼作呢?

方法其實不少,在個人項目中,我用到一個存儲過程<無論你用什麼,你如今要作的就是返回:當前頁碼的 10 條數據,及數據表總記錄條數>

我用到的存儲過程爲:請參考個人上篇博客

有了存儲過程,咱們就要用EF執行這個存儲過程,怎麼執行呢?

接口層:

IEnumerable<StudentModel> GetPagePro(string tableName, string fields, string orderField, string sqlWhere, int pageSize, int pageIndex, out int totalPage, out int RecordCount);

執行層:繼承接口

複製代碼
        /// <summary>
        /// EF執行存儲過程
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="fields">所要查詢的字段</param>
        /// <param name="orderField">排序字段</param>
        /// <param name="sqlWhere">條件語句 where</param>
        /// <param name="pageSize">頁容量</param>
        /// <param name="pageIndex">頁碼</param>
        /// <param name="totalPage">out參數 總分頁數量</param>
        /// <param name="RecordCount">out 參數 總記錄數</param>
        /// <returns></returns>
        public IEnumerable<StudentModel> GetPagePro(string tableName, string fields, string orderField, string sqlWhere, int pageSize, int pageIndex, out int totalPage, out int RecordCount)
         {
            using (StudentEntities context = new StudentEntities())
            {
                SqlParameter[] parameters = {
                    new SqlParameter("@TableName", SqlDbType.NText),
                    new SqlParameter("@Fields", SqlDbType.NText),
                    new SqlParameter("@OrderField", SqlDbType.NText),
                    new SqlParameter("@sqlWhere", SqlDbType.NText),
                    new SqlParameter("@pageSize", SqlDbType.Int),
                    new SqlParameter("@pageIndex", SqlDbType.Int),
                    new SqlParameter("@TotalPage", SqlDbType.Int),
                    new SqlParameter("@RecordCount", SqlDbType.Int)
                    };
                parameters[0].Value = tableName;
                parameters[1].Value = fields;
                parameters[2].Value = orderField;
                parameters[3].Value = sqlWhere;
                parameters[4].Value = pageSize;
                parameters[5].Value = pageIndex;
                parameters[6].Direction = ParameterDirection.Output;
                parameters[7].Direction = ParameterDirection.Output;
                var data = context.Database.SqlQuery<StudentModel>("exec [ZXL_GetPageData] @TableName,@Fields,@OrderField,@sqlWhere,@pageSize,@pageIndex,@TotalPage out,@RecordCount out", parameters).ToList();
                int count = data.Count;
                //
                string n6 = parameters[6].Value.ToString();
                string n7 = parameters[7].Value.ToString();
                //
                totalPage = !string.IsNullOrEmpty(n6) ? int.Parse(n6) : 0;
                RecordCount = !string.IsNullOrEmpty(n7) ? int.Parse(n7) : 0;
                return data;
            }
        }
複製代碼

實體Model層:

複製代碼
    public class StudentModel
    {
        public int Id { get; set; }
        public string StuNum { get; set; }
        public string deptNum { get; set; }
        public string StuName { get; set; }
        public string StuSex { get; set; }
        public Nullable<System.DateTime> AddTime { get; set; }
    }
複製代碼

控制器代碼:

複製代碼
        public ActionResult Index(int page=1)//查詢全部學生數據
        {
            int totalPage=0;
            int recordCount=0;
            var  data = studentdb.GetPagePro("Student", "*", "Id", "", 10, page, out totalPage, out recordCount);
            var studentList = new StaticPagedList<StudentModel>(data,page,10,recordCount);
            return View(studentList);//
        }
複製代碼

UI/View層

複製代碼
@model PagedList.StaticPagedList<Test.Model.StudentModel>
@using PagedList.Mvc
@using PagedList
@{
    ViewBag.Title = "Index";
    Layout = null;
}
<link href="~/Content/PagedList.css" rel="stylesheet" />
<style type="text/css">
    body {
        font-size: 12px;
        font-family: "微軟雅黑";
        color: #555;
        position: relative;
        background: #fff;
    }

    a {
        text-decoration: none;
        color: #555;
    }

    #tbList {
        border: 1px solid none;
        width: 800px;
        margin: 10px auto;
        border-collapse: collapse;
    }

        #tbList th, td {
            border: 1px solid #ccc;
            padding: 5px;
            text-align: center;
        }

    tfoot tr td {
        border: none;
    }
</style>

@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
    <div style="text-align: center;">
        <h1>Mvc分頁例子</h1>
        <table id="tbList">
           @* <thead>
                <tr>
                    <th>
                        <input id="StuName" name="StuName" type="text" placeholder="請輸入姓名" />
                    </th>
                    <th>
                        <input id="StuNum" name="StuNum" type="text" placeholder="請輸入學號" />
                    </th>
                    <th>
                        <input id="Submit1" type="submit" value="submit" />
                    </th>
                </tr>
            </thead>*@

            <tbody>
                @if (Model.Count() != 0)
                {  
                    <tr>
                        <th>姓名
                        </th>
                        <th>性別
                        </th>
                        <th>學號
                        </th>
                    </tr>
                    foreach (var item in Model)
                    {   
                    <tr style="text-align: center;">
                        <td>
                            @Html.DisplayFor(modelItem => item.StuName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.StuSex)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.StuNum)
                        </td>
                    </tr>  
                    }

                }
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="5">
                        <div class="">
                            @if (Model != null)
                            {  
                                <span style="height: 20px; line-height: 20px;">共 @Model.TotalItemCount.ToString() 條記錄,當前第 @Model.PageNumber 頁/共 @Model.PageCount 頁 </span>  
                                @Html.PagedListPager(Model, page => Url.Action("Index", new { page }), new PagedListRenderOptions() { LinkToFirstPageFormat = "首頁", LinkToNextPageFormat = "下一頁", LinkToPreviousPageFormat = "上一頁", LinkToLastPageFormat = "末頁", DisplayItemSliceAndTotal = false, MaximumPageNumbersToDisplay = 3 })    
                            }
                        </div>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
}
複製代碼

上述代碼已經很齊全了,你們能夠自行嘗試,須要說明兩點:

控制器代碼:

view層HTML代碼:

至此,整個pagedList分頁就完畢了。

這樣查詢提高了效率。

個人分頁效果圖以下:

由圖可知,個人數據表共有:151303條記錄,若是採用每次都加載全部數據,效率是何其低可想而知。

呵呵,截止到這兒,pagedlist分頁也就講完了!

如今,咱們提出新的要求:結合查詢,根據學生姓名和學號進行模糊查詢

其後端變動以下:

複製代碼
        public ActionResult Index(int page = 1, string StuName = "", string StuNum = "",string sortOrder="")//查詢全部學生數據
        { 
            string where = string.Empty;
            if (!string.IsNullOrEmpty(StuName))
            {
                ViewBag.StuName = StuName;
                where += " and StuName like '%" + StuName + "%'";
            }
            if (!string.IsNullOrEmpty(StuNum))
            {
                ViewBag.StuNum = StuNum;
                where += " and StuNum like '%" + StuNum + "%'";
            }
            int totalPage = 0;
            int recordCount = 0;
            var data = model.GetPagePro("Student", "*", "Id", " 1=1 " + where, 10, page, out totalPage, out recordCount);
            
            var studentList = new StaticPagedList<StudentModel>(data, page, 10, recordCount);
            return View(studentList);//
        }
複製代碼

前端以下:

複製代碼
@model PagedList.StaticPagedList<Test.Model.StudentModel>
@using PagedList.Mvc
@using PagedList
@{
    ViewBag.Title = "Index";
    Layout = null;
}
<link href="~/Content/PagedList.css" rel="stylesheet" />
<style type="text/css">
    body {
        font-size: 12px;
        font-family: "微軟雅黑";
        color: #555;
        position: relative;
        background: #fff;
    }

    a {
        text-decoration: none;
        color: #555;
    }

    #tbList {
        border: 1px solid none;
        width: 800px;
        margin: 10px auto;
        border-collapse: collapse;
    }

        #tbList th, td {
            border: 1px solid #ccc;
            padding: 5px;
            text-align: center;
        }

    tfoot tr td {
        border: none;
    }
</style>

@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
    <div style="text-align: center;">
        <h1>Mvc分頁例子</h1>
        <table id="tbList">
            <thead>
                <tr>
                    <th>
                        <input id="StuName" name="StuName" type="text" placeholder="請輸入姓名" value="@ViewBag.StuName" />
                    </th>
                    <th>
                        <input id="StuNum" name="StuNum" type="text" placeholder="請輸入學號" value="@ViewBag.StuNum" />
                    </th>
                    <th>
                        <input id="Submit1" type="submit" value="submit" />
                    </th>
                </tr>
            </thead>

            <tbody>
                @if (Model.Count() != 0)
                {  
                    <tr>
                        <th>姓名
                        </th>
                        <th>性別
                        </th>
                        <th>學號
                        </th>
                    </tr>
                    foreach (var item in Model)
                    {   
                    <tr style="text-align: center;">
                        <td>
                            @Html.DisplayFor(modelItem => item.StuName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.StuSex)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.StuNum)
                        </td>
                    </tr>  
                    }

                }
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="5">
                        <div class="">
                            @if (Model != null)
                            {  
                                <span style="height: 20px; line-height: 20px;">共 @Model.TotalItemCount.ToString() 條記錄,當前第 @Model.PageNumber 頁/共 @Model.PageCount 頁 </span>  
                                @Html.PagedListPager(Model, page => Url.Action("Index", new { page,StuName=ViewBag.StuName,StuNum=ViewBag.StuNum }), new PagedListRenderOptions() { LinkToFirstPageFormat = "首頁", LinkToNextPageFormat = "下一頁", LinkToPreviousPageFormat = "上一頁", LinkToLastPageFormat = "末頁", DisplayItemSliceAndTotal = false, MaximumPageNumbersToDisplay = 3 })    
                            }
                        </div>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
}
複製代碼

上圖爲變動處、

運行效果:

相關文章
相關標籤/搜索