SportsStore的mvc3分页示例

2012-02-01

SportsStore的mvc3分页示例,使用Linq实现,很简洁有效,所以拿来分享一下

1.Controller代码

using System.Linq;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;

namespace SportsStore.WebUI.Controllers {

public class ProductController : Controller {
public int PageSize = 4; // We will change this later
private IProductRepository repository;

public ProductController(IProductRepository repoParam) {
repository = repoParam;
}

public ViewResult List(int page = 1) {
return View(repository.Products
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize));
}
}
}

2.Models部分代码

using System;

namespace SportsStore.WebUI.Models {

public class PagingInfo {
public int TotalItems { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }

public int TotalPages {
get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); }
}
}
}

3.添加HtmlHelper

using System;
using System.Text;
using System.Web.Mvc;
using SportsStore.WebUI.Models;

namespace SportsStore.WebUI.HtmlHelpers {

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.TotalPages; i++) {
TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
result.Append(tag.ToString());
}

return MvcHtmlString.Create(result.ToString());
}
}
}

4.调用示例 这里用的单元测试框架

http://localhost:23081/?page=2 

[TestMethod]
public void Can_Generate_Page_Links() {

// Arrange - define an HTML helper - we need to do this
// in order to apply the extension method
HtmlHelper myHelper = null;

// Arrange - create PagingInfo data
PagingInfo pagingInfo = new PagingInfo {
CurrentPage = 2,
TotalItems = 28,
ItemsPerPage = 10
};

// Arrange - set up the delegate using a lambda expression
Func<int, string> pageUrlDelegate = i => "Page" + i;

// Act
MvcHtmlString result = myHelper.PageLinks(pagingInfo, pageUrlDelegate);

// Assert
Assert.AreEqual(result.ToString(), @"<a href=""Page1"">1</a><a class=""selected""
href=""Page2"">2</a><a href=""Page3"">3</a>");
}

作者:robotbird, 分类:关于代码 标签: donet mvc , 浏览(3900), 评论(2)
上一篇: 2011年总结与2012年展望
下一篇: 从今天开始坚持不刷技术类文章

相关文章

(2)条评论 订阅

  1. ${item.nickname} 币安链 说:

    使用Linq实现,很简洁有效。

  2. ${item.nickname} csonla 说:

    请问一下这个是高效模式吗?还是每次都要取出所有数据?

1

发表评论

电子邮件用于回复通知和avatar全球唯一头像 *

*