AI智能
改变未来

ASP.Net mvc分页查询实战

  1. 分页查询控制器
  2. 分页查询前台界面
  3. 分页查询JS代码

分页查询控制器

public ActionResult Index(int pageIndex=1,int pageSize=10,string name=\"\"){//获取总记录数var totalRows = db.Roles.Count();//计算总页数var totalPages = Math.Ceiling(totalRows * 1.00 / pageSize);ViewBag.totalPages = totalPages;var roles = db.Roles.Where(p=>p.Name.Contains(name)).OrderBy(p=>p.ID)  //排序.Skip((pageIndex-1) * pageSize)    //跳过.Take(pageSize)   //取.ToList();ViewBag.pageIndex = pageIndex; //将当前页又返回前台ViewBag.name = name;  //将查询条件返回,将查询条件固定,防止当你要根据名字查询    //是,点击下一页或其他功能,又重新刷新,没有根据名称查询ViewBag.pageSize = pageSize;//一页显示几条数据,固定下拉框中的值并判断选择当前选择的一页查询条数return View(roles);}

前台代码

@{
ViewBag.Title = “Index”;
}

名称:/value=\”@ViewBag.name\” 固定查询条件,防止查询条件因页面刷新刷新@foreach (var item in Model){}

编号 名称 备注
@item.ID @item.Name @item.Remark
  • 共 @ViewBag.totalPages 页,第页,每页显示
    <select id=\"pageSize\" onchange=\"page(1);\">@{var listPageSize = new List<int> { 5, 10, 20, 50, 100 };}@foreach (var item in listPageSize){if (@ViewBag.pageSize == @item) //判断当前页是否等于下拉框的值,等于则选中selected=\"selected\" 固定该值{<option value=\"@item\" selected=\"selected\">@item</option>}else{<option value=\"@item\">@item</option>}}</select>条</li></ul><ul class=\"pagination\"><li class=\"page-item \"><a class=\"page-link\" href=\"javascript:page(1);\" tabindex=\"-1\" aria-disabled=\"true\">首页</a></li>//上页当前页+1  当小于第一页是 禁用disabled@if (@ViewBag.pageIndex > 1){<li class=\"page-item\"><a class=\"page-link\" href=\"javascript:page(@ViewBag.pageIndex-1);\">上页</a></li>}else{<li class=\"page-item disabled\"><a class=\"page-link\" href=\"javascript:page(@ViewBag.pageIndex-1);\">上页</a></li>}<li class=\"page-item \" aria-current=\"page\"><span class=\"page-link\"> @ViewBag.pageIndex</span></li>//下页当前页-1  当大于最大页是 禁用disabled@if (@ViewBag.pageIndex < @ViewBag.totalPages){<li class=\"page-item \" aria-current=\"page\"><a class=\"page-link\" href=\"javascript:page(@ViewBag.pageIndex+1);\">下页 </a></li>}else{<li class=\"page-item disabled\" aria-current=\"page\"><a class=\"page-link\" href=\"javascript:page(@ViewBag.pageIndex+1);\">下页 </a></li>}//末页跳到最大页 @ViewBag.totalPages<li class=\"page-item\"><a class=\"page-link\" href=\"javascript:page(@ViewBag.totalPages);\">末页</a></li><li class=\"page-item\"><input type=\"button\" class=\"page-link\" value=\"GO\" onclick=\"go()\" /></li></ul>

# js代码

@section scripts{<script>function page(pageIndex) {var name = $(\"#txtCondName\").val(); //获取搜索框的值var pageSize = $(\"#pageSize\").val(); //获取下拉框的值window.location.href = \"/role/index?pageindex=\" + pageIndex+ \"&pageSize=\" + pageSize + \"&name=\" + name;}function go() {//获取输入的页码的值var pageIndex = $(\"#pageIndex\").val();page(pageIndex);}</script>}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » ASP.Net mvc分页查询实战