方法一:
在项目中增加App_Code文件夹,新增一个MyHtmlper.cshtml视图文件
写入代码:
@helper Pagger(int pageIndex, int pageCount)
{
<div>
@for (int i = 1; i <= pageCount; i++)
{
if (i != pageIndex)
{
<span > <a href="/Home/Index/@(i)_@(pageCount)">@(i)</a></span>
}
else
{
<span >@i</span>
}
}
</div>
}
新增一个HomeController
public class HomeController : Controller
{
// GET: Home
public ActionResult Index(int pageIndex = 1,int pageCount=10)
{
if (pageIndex <= 0)
pageIndex = 1;
TempData["PageIndex"] = pageIndex;
TempData["PageCount"] = pageCount;
return View();
}
}
写一个新的路由
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Pagger",
url: "{controller}/{action}/{pageIndex}_{pageCount}",
defaults: new { controller = "Home", action = "Index"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
新增视图:
@{
ViewBag.Title = "Index";
}
@{
var pageindex = Convert.ToInt32( TempData["PageIndex"]);
var pageCount = Convert.ToInt32(TempData["PageCount"]);
}
<div>
当前是第 @pageindex 页
</div>
<hr/>
@MyHtmlper.Pagger(pageindex, pageCount)
运行结果
方法二:
扩展HtmlHelper方法,新增一个CodeHelper类型,扩展HtmlHelper一个Pagger方法
public static class CodeHelper
{
public static MvcHtmlString Pagger(this HtmlHelper htmlHelper, int pageIndex, int pageCount)
{
var htmlSb = new StringBuilder();
for (int i = 1; i <= pageCount; i++)
{
if (i != pageIndex)
{
htmlSb.Append(" <span> <a href =\"/Home/Index/" + i + "_" + pageCount + "\" >" + i + "</a></span>");
}
else
{
htmlSb.Append("<span>" + i + "</span>");
}
}
return new MvcHtmlString(htmlSb.ToString());
}
}
修改视图
@{ ViewBag.Title = "Index"; } @{ var pageindex = Convert.ToInt32( TempData["PageIndex"]); var pageCount = Convert.ToInt32(TempData["PageCount"]); } <div> 当前是第 @pageindex 页 </div> <hr/> @MyHtmlper.Pagger(pageindex, pageCount) <hr/> @Html.Pagger(pageindex,pageCount)
运行结果:
本人当前只知道两种方法。分享出了给大家借鉴