Asp.NET MvC EF實現分頁


打開Visual Studio 2017 選擇 項目----->管理nuget包  其他版本也有

輸入paged 下載安裝 pagedList和pagedList.mvc

 

 在model文件新建一個分頁的類比如課程:

 1 //要引入PagedList命名空間
 2 using PagedList;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Web;
 7 
 8 namespace jiaowu.Models
 9 {
10     public class ViewCourse
11     {
12         //創建課程對象
13         public IPagedList<Course> Course { get; set; }
14         /**條件**/
15         //按姓名查詢
16         public string Name { get; set; }
17         //排序條件
18         public string SortBy { get; set; }
19 
20     }
21 }

在中控制器中

 1  /// <summary>
 2        /// 查詢課程信息
 3        /// </summary>
 4        /// <param name="Name">課程名字</param>
 5        /// <param name="page">當前頁</param>
 6        /// <returns></returns>
 7         public ActionResult CourseList(string Name,int? pageIndex)
 8         {
 9             //查詢所有的課程列表
10             var coures = en.Courses.OrderBy(m => m.Id);
11             //每頁顯示的數量
12             const int pageItems =4;
13             //當前頁
14             int currentPage = (pageIndex ?? 1);
15             //查詢所有的課程信息
16             IPagedList<Course> pageCoures = coures.ToPagedList(currentPage, pageItems);
17             //實例花一個ViewCourse的對象
18             ViewCourse vcourse = new ViewCourse();
19             
20             //判斷用戶名是否為空
21             if (string.IsNullOrEmpty(Name))
22             {
23                 //為空查詢所有
24                 vcourse.Course = pageCoures;
25             }
26             else
27             {
28                 //不為空根據姓名查詢
29                 vcourse.Course = pageCoures.Where(m => m.Name == Name).ToPagedList(currentPage,pageItems); ;
30             }
31             return View(vcourse);
32         }
33             

View視圖中

1 <div style="width:1040px">
2         <div style="float:right">
3             @Html.PagedListPager(Model.Course, page => Url.Action("CourseList", new { Name = Model.Name, page }))
4         </div>
5         <div style="float:right;margin-top:28px;margin-right:10px">
6             第 @(Model.Course.PageCount < Model.Course.PageNumber ? 0 : Model.Course.PageNumber) 頁 共 @Model.Course.PageCount  頁
7         </div>
8
9     </div>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM