/// <summary> /// 扩展HtmlHelper /// </summary> /// <param name="html"></param> /// <param name="pagingInfo"></param> /// <param name="pageUrl">根据页面索引生成url的委托</param> /// <returns>分页链接</returns> 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"); //创建一个<a>标签 tag.MergeAttribute("href", pageUrl(i)); //设置a标签的href属性 tag.InnerHtml = i.ToString(); //设置a标签的文本节点 if (i==pagingInfo.CurrentPage) //设置当前页的Class { tag.AddCssClass("selected"); } result.Append(tag.ToString()); } return MvcHtmlString.Create(result.ToString()); }
public void Can_Generate_Page_Links() { //布置——定义一个HTML辅助器方法 HtmlHelper myHelper = null; //布置——创建PagingInfo数据 PagingInfo pagingInfo = new PagingInfo { CurrentPage = 2, TotalItems = 28, ItemsPerPage = 10 }; //布置——建立委托 Func<int, string> pageUrlDelegate = i => "Page" + i; //动作 MvcHtmlString result = myHelper.PageLinks(pagingInfo, pageUrlDelegate); //断言 Assert.AreEqual(result.ToString(),@"<a href=""Page1"">1</a><a class=""selected"" href=""Page2"">2</a><a href=""Page3"">3</a>"); }