步骤一:在视图模型中建立一个分页信息类(PagingInfo)
public class PagingInfo
{
public int TotalItems { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public int TotalPage
{
get
{
return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage);
}
}
}
步骤二:新增一个html辅助器方法(PageLinks)
public static class PagingHelpers
{
public static MvcHtmlString PageLinks(this HtmlHelper html,PagingInfo pagingInfo,Func<int,string> pageUrl)
{
StringBuilder result = new StringBuilder();
for (int i = 1; i <=pagingInfo.TotalPage; i++)
{
TagBuilder tag = new TagBuilder("a");
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
{
tag.AddCssClass("selected");
tag.AddCssClass("btn-primary");
}
tag.AddCssClass("btn btn-default");
result.Append(tag.ToString());
}
return MvcHtmlString.Create(result.ToString());
}
}
步骤三:添加视图的模型数据(ProductListViewModel)
public class ProductListViewModel
{
public IEnumerable<Product> Products { get; set; }
public PagingInfo PagingInfo { get; set; }
}
备注:Product类是域模型中的一个实体类
步骤四:新增控制器(Product),并且在控制器中新增动作(List)
public class ProductController : Controller
{
private IProductsRepository repository;
public ProductController(IProductsRepository productRepository)
{
this.repository = productRepository;
}
public int PageSize = 4;
public ViewResult List( int Page=1)
{
ProductListViewModel model = new ProductListViewModel
{
Products = repository.Products
.OrderBy(p => p.ProductID)
.Skip((Page - 1) * PageSize)
.Take(PageSize),
PagingInfo =new PagingInfo
{
CurrentPage=Page,
ItemsPerPage=PageSize,
TotalItems=repository.Products.Count()
}
};
return View(model);
}
}
步骤五:新增视图(List),在视图中显示数据
@model ZlzStore.WebUI.Models.ProductListViewModel
@using ZlzStore.WebUI.HtmlHelpers
@{
ViewBag.Title = "Products";
}
<div>
@foreach (var p in Model.Products)
{
<div>
<h3>@p.Name</h3>
@p.Description
<h4>@p.Price.ToString("c")</h4>
</div>
}
</div>
<hr />
<div>
@Html.PageLinks(Model.PagingInfo,x=>Url.Action("List",new { Page=x}))
</div>
以上就实现了简单分页功能.供以后参考!