MVC快速分页
2016-03-06 06:57
281 查看
using System; namespace CWHomeWebSite.Models { public class PagingInfo { //项目总数量 public int TotalItems { get; set; } //当前索引 public int PageIndex { get; set; } //分页大小 public int PageSize { get; set; } //页数 public int PageCount { get { return (int)Math.Ceiling((decimal)TotalItems / PageSize); } } } }
创建视图对应的ViewModel
using CWHomeWebSite.Data.Entities; using System.Collections.Generic; namespace CWHomeWebSite.Models { public class PostViewModel { //博客集合 public IEnumerable<Post> Posts { get; set; } //分页参数 public PagingInfo PagingInfo { get; set; } } }
处理Controller视图方法
public ActionResult Index(int pageIndex = 1, int pageSize = 2) { //获取当前分页数据集合 var posts = this.repository.Posts .OrderBy(p=>p.UpdateTime) .Skip((pageIndex - 1) * pageSize) .Take(pageSize); //将当前ViewModel传递给视图 return View(new PostViewModel { Posts = posts, PagingInfo = new PagingInfo { TotalItems = this.repository.Posts.Count(), PageIndex = pageIndex, PageSize = pageSize } }); }
在View中通过Html辅助器扩展方法处理PagingInfo
using CWHomeWebSite.Models; using System; using System.Web.Mvc; namespace CWHomeWebSite.Helper { public static class PagingHelper { //HtmlHelper扩展方法,用于分页 public static MvcHtmlString Pagination(this HtmlHelper html, PagingInfo pageInfo,Func<PagingInfo,string> pageLinks) { var htmlString = pageLinks(pageInfo); return MvcHtmlString.Create(htmlString); } } }
@model CWHomeWebSite.Models.PostViewModel @using CWHomeWebSite.Helper @{ ViewBag.Title = "主页"; } <!-- 博客列表 --> <section id="one"> <ul class="actions"> @foreach (var post in Model.Posts) { <li> <header class="major"> <h2> @post.Title <br /> | @post.CreateTime.ToShortDateString() </h2> <p>@post.Description</p> <ul class="actions"> <li>@Html.ActionLink("更多", "Detail", "Home", new { @post.PostId }, new { @class = "button" })</li> </ul> </header> <hr /> </li> } </ul> <!--分页代码--> @Html.Pagination(Model.PagingInfo, (info) => { var pagingString = "<ul class=\"actions small\">"; for (var i = 1; i <= info.PageCount; i++) { if (i == info.PageIndex) { pagingString += "<li><a class=\"special\" href=\"#\">" + i + "</a></li>"; } else pagingString += "<li><a class=\"normal\" href=\"" + Url.Action("Index", new { pageIndex = i, pageSize = info.PageSize }) + "\">" + i + "</a></li>"; } pagingString += "</ul>"; return pagingString; }) </section> <!--最近作品--> @Html.Action("RecentWorks", "Work")
url跳转:
@Url.Action("Index", "Home", new { id=1})“生成的html是:”生成的url为: /Home/Index/1“
相关文章推荐
- MVC, MVP与MVVM
- 3698: XWW的难题 有源汇上下界最大流
- 面试题
- [leetcode] 325. Maximum Size Subarray Sum Equals k 解题报告
- C语言程序设计
- 如何设置约束让三个按钮平分UIView容器的宽度
- C语言数据类型
- 55. Jump Game
- 思考下:工作沟通工具的选择(QQ?、微信?、邮件?、m2m还是其他的?)
- c语言题中的一些陷阱
- 只需2个公式,3阶魔方7步还原法
- [leetcode] 297. Serialize and Deserialize Binary Tree 解题报告
- 夺命雷公狗---微信开发44----用户分组管理接口(实例)
- 插入排序法 php
- 自定义一个只显示年月的DatePicker(UIDatePicker无法实现年月显示)
- 分支限界法求解旅行商问题
- 观察者模式
- Sublime test配置php运行环境
- FLC-Regular Grammar
- LeetCode Reverse Words in a String II