我认为您尝试使用错误的方面来完成工作,这就是为什么您发现实现起来很痛苦。
获取整个对象集合然后渲染它们的子集非常浪费,您怎么知道您的用户会查看所有页面?如果有 10,000 个对象怎么办?
您想从数据库中检索 2 条信息、对象的第一页和对象总数的计数 - 这应该从您的控制器处理(最好通过调用某种形式的服务而不是直接调用数据库,但那是另一天的论据)。将该信息打包到一个包含您需要的任何渲染助手的类中,并将该类发送到视图。给定对象数量和页面大小,您可以构建简单的导航链接,这些链接返回到传递新页码的操作。
public class GridView<T>
{
private Dictionary<string, Func<T, string> _columnMap;
public GridView( IEnumerable<T> items, long totalItems, long currentPage )
{
Items = items;
Count = totalItems;
CurrentPage = currentPage;
}
public long Count { get; private set; }
public long CurrentPage { get; private set; }
public IEnumerable<string> Columns { get; }
public IEnumerable<T> Items { get; private set; }
public void AddColumn( string name, Func<T, string> data )
{
_columnMap.Add( columnName, data );
}
public string GetColumnValue( string name, T item )
{
var valueExtractor = _columnMap[name];
return valueExtractor(item);
}
public string GetPageCount()
{
// Calculate page count, convert to string and return
}
// Might be easier to make these two extension methods for the html helper class
// so that you get easier access to the context of the current action
public string GetPreviousLink()
{
}
public string GetNextLink()
{
}
}
在控制器中...
// Use the route definition to set the page to default to 1
public ActionResult ShowProducts( int page )
{
// Get the list of products for the requested page
var currentPageData = ...
// Get the total number of products
var productCount = ...
var gridData = new GridView<Product>( currentPageData, productCount, page );
gridData.AddColumn( "Name", p => p.ProductName );
gridData.AddColumn( "Price", p => p.Price.ToString("c") );
gridData.AddColumn( "In Stock", p => p.StockLevel.ToString());
return View( gridData );
}
视图中的某处...
<% =Html.RenderPartial( "GridView", Model ) %>
在部分...
<table>
<tr>
<% foreach( var column in Model.Columns ) { %>
<th><% =column %></td>
<% } %>
</tr>
<% foreach( var item in Model.Items ) { %>
<tr>
<% foreach( var column in Model.Columns ) { %>
<td><% =Model.GetColumnValue( column, item ) %></td>
<% } %>
<tr>
<% } %>
<tr>
<td colspan="<% =Model.Columns.Count %>">Showing Page <% =Model.CurrentPage %> of <% =Model.GetPageCount() %></td>
</tr>
<tr>
<td colspan="<% =Model.Columns.Count %>"><% =Model.GetPreviousLink() %> | <% =Model.GetNextLink() %></td>
</tr>
</table>
请注意,所有显示的代码都是空代码,不保证可以正常工作,只是演示了一系列概念。