.net MVC4 来一个简单的分页代码
action
VodeEntities db = new NewVode.Models.VodeEntities(); int pagesize = 3; public ActionResult Index(string title, int page = 1) { var sql = "select * ,row_number() over ( order by id desc ) as rownum from vode"; if (!string.IsNullOrEmpty(title)) { sql = string.Format("{0} where title like '%{1}%'", sql, title); } var conn = db.Database.Connection; var sql2 = string.Format("select top {1} * from ({0}) as a where a.rownum>({2}-1)*{1} and a.rownum<={1}*{2}", sql, pagesize, page); var list = conn.Query<Vode>(sql2); ViewBag.curPage = page; var total = conn.QueryFirst<int>("select count(id) from (" + sql + ") as a"); ViewBag.curPageTotal =Math.Ceiling((double)( total / pagesize)); ViewBag.stitle = title; return View(list); }
html
@model IEnumerable<NewVode.Models.Vode> @{ ViewBag.Title = "Index"; } <script src="~/Scripts/jquery-1.8.2.js"></script> <h2>Index</h2> <form action="/home/index" method="post"> 标题: <input name="title" id="title" value="@ViewBag.stitle" /> <input type="button" value="查询 " id="btnSearch"/> <input type="hidden" id="page" name="page" value="@ViewBag.curPage" /> @if (Model.Count() == 0) { <div> 无数据 </div> } else { <div> @foreach (var item in Model) { <div> @item.title </div> } <div id="pagebar"> <a href="javascript:;" onclick="goto(-1)" id="prev">上一页</a> <a href="javascript:;" onclick="goto(1)" id="next">下一页</a> <select> @for (int i = 1; i <= ViewBag.curPageTotal; i++) { <option value="@i">@i</option> } </select> </div> </div> } </form> <script> var curpage = parseInt( @ViewBag.curPage); var total = parseInt(@ViewBag.curPageTotal); if (total <=1) { $("#pagebar").hide(); } else { if (curpage == 1) { $("#prev").disabled = true; } if (curpage == total) { $("#next").hide(); } } function goto(v) { var n = curpage + v; if (n <= 0) { alert("已经是第一页了"); } else if (n > total) { alert("已到最后一页了"); } else { $("#page").val(n); $("form").submit(); } } $("form select").val(curpage).change(function () { $("#page").val($(this).val()); $("form").submit(); }); $("#btnSearch").click(function () { $("#page").val(1); $("form").submit(); }) </script>