关于MVC3.0分页的问题
最近才刚开始了解MVC3.0,尝试做一下分页功能,能解释一下MVC的分页思想吗,有实例更好了,谢谢大家了
[解决办法]
Controller
public ActionResult Index(int? id = 1)
{
var count = db.Manager.Count();
var article = db.Manager.OrderByDescending(m => m.ID)
.Skip(5 * Convert.ToInt32(id - 1))
.Take(5);
ViewBag.Current = id;
ViewBag.Count = (count % 5 == 0) ?
(count / 5) : count / 5 + 1;
return View(article);
//var managerslist = db.Manager.ToList();
//return View(managerslist);
}
@Html.Pager(1, current, count, 5)
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XikeCompany.Models;
using System.Text;
using System.Web.Routing;
namespace System.Web.Mvc
{
public static class WebPager
{
/// <summary>
/// 创建分页链接
/// </summary>
/// <param name="helper">HtmlHelper类</param>
/// <param name="startPage">开始页 (多数情况下是 1)</param>
/// <param name="currentPage">当前页</param>
/// <param name="totalPages">总页数</param>
/// <param name="pagesToShow">前后显示的页数</param>
public static MvcHtmlString Pager(this HtmlHelper helper, int startPage, int currentPage, int totalPages, int pagesToShow)
{
RouteData routeData = helper.ViewContext.RouteData;
//你可能还要获取action
//routeData.Values["action"].ToString();
string controller = routeData.Values["controller"].ToString();
StringBuilder html = new StringBuilder();
//创建从第一页到最后一页的列表
html = Enumerable.Range(startPage, totalPages)
.Where(i => (currentPage - pagesToShow) < i & i < (currentPage + pagesToShow))
.Aggregate(new StringBuilder(@"<div class=""pagination""><span>共" + totalPages + "页</span>"), (seed, page) =>
{
//当前页
if (page == currentPage)
seed.AppendFormat(@"<span class=""current"">{0}</span>", page);
else
{
//第一页时显示:domain/archives
if (page == 1)
{
seed.AppendFormat("<a href="/{0}">{1}</a>", controller.ToLower()+"/Index", page);
}
else
{
seed.AppendFormat("<a href="/{0}/{1}">{1}</a>", controller.ToLower() + "/Index", page);
}
}
return seed;
});
html.Append(@"</div>");
return MvcHtmlString.Create(html.ToString());
}
}
}