标签:
Model里的代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Mvc翻页查询.Models { public class CarBF { private masterDataContext _Context = new masterDataContext(); public List<Car> Select(int pageSize,int pageNo) { //下面这个查询语句的意思是去掉前三行,查询下一页,而每页为三行数据 //select top 3* from Car where Code not in (select top 3 Code from car) //pageSize是定义每页为几行,pageNo是需要查询第几页 var query = _Context.Car.Skip(pageSize*(pageNo-1)).Take(pageSize); return query.ToList(); } public int GetPageCount(int pageSize) { //获取总行数 int rowsCount = _Context.Car.Count(); //根据自定义的一页为几行和总行数来计算要分几页,并转为最大整数 int pageCount =(int) Math.Ceiling(1.0*rowsCount/pageSize); //返回需要分开多少页 return pageCount; } } }
控制器里的代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Mvc翻页查询.Models; namespace Mvc翻页查询.Controllers { public class HomeController : Controller { // // GET: /Home/ //定义每页的数据是两行,常量 private const int PageSize = 2; public ActionResult Index(int id) //id是从视图传回来的值,需要查询第几页。程序刚考试运行的时候,在路由里给id 赋初始值为1 { //首先判断这个表要分成几页 int pagecount = new CarBF().GetPageCount(PageSize); //把值传到视图中 ViewBag.PageNo = id; ViewBag.PageCount = pagecount; //定义一个int类型的集合 List<int> pagelist = new List<int>(); //把每一条数据都放在pagelist这个集合里 for (int i = 1; i < pagecount; i++) { pagelist.Add(i); } //再把分页后的内容放在下拉表里 SelectList selectlist = new SelectList(pagelist,id); //把数据传dao视图 ViewBag.PageList= selectlist; //调用BF的查询方法,参数是自定义的每页有几条数据和需要查询第几页,并把值传到视图 List<Car> list = new CarBF().Select(PageSize,id); return View(list ); } } }
视图里的代码
@using Mvc翻页查询.Models; @model List<Car> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>分页查询</title> </head> <body> <div> <ol> @foreach (Car data in Model) { <li>@data.Name</li> } </ol> @{ int PageCount = (int)ViewBag.PageCount; @* 要分成几页*@ int NowPage = (int)ViewBag.PageNo; @* 当前的页*@ int PrevPage = NowPage - 1;@*上一页*@ int NextPage = NowPage + 1;@*下一页*@ } @Html.ActionLink("首页", "Index", "Home", new { id=1},null); @*查询首页,第一页*@ @*判断上一页是不是首页,如果是首页就不变了*@ @Html.ActionLink("上一页", "Index", "Home", new { id=PrevPage},new{onclick=(PrevPage<=0?"return false":"return true")}); @Html.ActionLink("下一页", "Index", "Home", new {id=NextPage },new{onclick=(NextPage>PageCount?"return false":"return true")}); @Html.ActionLink("尾页","Index","Home",new{id=PageCount},null); @* 下拉列表的显示方法,点击的时候触发一个Js事件,就是把值传回控制器调用方法啊,并返回视图*@ 转向 @Html.DropDownList("pageid",ViewBag.PageList as SelectList,new {onchange="dochange()"})页 </div> </body> </html> <script src="~/jquery-1.11.2.min.js"></script> <script> function dochange() { //把下拉列表里的值取出来 //var a = document.getElementById("pageid").value; // window.location.href("/Home/Index" + a); var a = $("#pageid").val(); alert(a); window.location.href="/Home/Index/" + a; } </script>
标签:
原文地址:http://www.cnblogs.com/275147378abc/p/4646381.html