一:UserController 后台查选数据
1.获取指定页数据
//PageSize代表一页有多少条数据,PageNo代表当前页数
public List<User> Select(int PageSize, int PageNo)
{
var db = new Context();
if (PageNo<=1) { PageNo = 1; }
List ulist = db.Users.Include(x => x.AuthorityRs).OrderBy(a => a.Id).Skip((PageNo - 1) * PageSize).Take(PageSize).ToList();//查选一页的数据
return ulist;
}
2.获取总页数
public int GetPageCount(int pageSize)//PageSize代表一页有多少条数据
{
var db = new Context();
int rowsCount = db.Users.Count();//总数据
int pageCount = (int)Math.Ceiling(1.0 * rowsCount / pageSize);//取天花板数
return pageCount;//页码数
}
详解:public int pageSizeCount = 5;//选择一页为5条数据
3. Index函数
public ActionResult Index(int? PageNo)
{
ViewBag.pageSize = pageSizeCount;
if (PageNo== null||PageNo<=0)
{
id = 1;/如果所传PageNo为或者小于0时,赋值为1
}
List list =Select(pageSizeCount, id.Value);//找出当前数据
int pageCount =GetPageCount(pageSizeCount);//找出总页数
int nextPageNo = id.Value >= pageCount ? pageCount : id.Value + 1;//计算下一页页号
int prevPageNo = id.Value == 1 ? 1 : id.Value - 1;//计算上一页页号
//使用viewbag带到视图去
ViewBag.NextPageNo = nextPageNo;
ViewBag.PrevPageNo = prevPageNo;
ViewBag.PageCount = pageCount;//总页数
ViewBag.PageNo = id;//当前页号
//下拉列表显示页数需要的selectlist数据 ListlistPage = new List();
for (int i = 1; i <= pageCount; i++)
{
listPage.Add(i);
}
SelectList li = new SelectList(listPage, id);
ViewBag.PageList = li;
return View(list);
}
2.前台显示:
共 @ViewBag.PageCount 页,当前是第 @ViewBag.PageNo 页
@Html.ActionLink("首页", "Index", new { PageNo = 1 })
@Html.ActionLink("上一页", "Index", "Process", new { PageNo = (int)ViewBag.PageNo - 1 }, null) @Html.ActionLink("下一页", "Index", "Process", new { PageNo = (int)ViewBag.NextPageNo }, null) @Html.ActionLink("尾页", "Index", new { PageNo = (int)ViewBag.PageCount })
@using (Html.BeginForm("Index", "Process")) {
@:转到:@Html.DropDownList("PageNo", (SelectList)ViewBag.Pagelist)
}