我試圖放在一起使用ASP.NET MVC的一個非常簡單的應用程序,顯示新聞文章和分頁他們。我有一些中途,但需要一些幫助,整理分頁,並使其與搜索查詢一起工作。(家庭作業)MVC分頁幫助
這裏是我的HomeController:
public ActionResult Index(String query, int? page)
{
// limit the number of articles per page
const int pageSize = 4;
// build the query
var ArticleQuery = from a in _db.ArticleSet select a;
// check if their is a query
if (!string.IsNullOrEmpty(query))
{
ArticleQuery = ArticleQuery.Where(a => a.headline.Contains(query));
}
// orders the articles
var OrderedArticles = ArticleQuery.OrderByDescending(a => a.posted);
// takes the ordered articles and paginates them
//var paginatedArticles = new PaginatedList(OrderedArticles.Skip((page ?? 0) * pageSize).Take(pageSize), page ?? 0, pageSize);
var paginatedArticles = new PaginatedList<Article>(OrderedArticles, page ?? 0, pageSize);
// return the paginated articles to the view
return View(paginatedArticles);
}
的想法是,控制器顯示4項每頁會按日期排序。這裏是我對索引方法的看法:
<ul id="pagination">
<% if (Model.PreviousPage) { %>
<li><%= Html.ActionLink("<< First Page", "Index")%></li>
<li><%= Html.ActionLink("<< Previous Page", "Index", new { page=(Model.PageIndex-1) }) %></li>
<% } %>
<% if (Model.NextPage) { %>
<li><%= Html.ActionLink("Next Page >>", "Index", new { page = (Model.PageIndex + 1) })%></li>
<li><%= Html.ActionLink("Last Page >>", "Index", new { page = (Model.TotalPages - 1) })%></li>
<% } %>
</ul>
想法是,這兩個分頁鏈接將只顯示條件爲真。
最後這裏是尋呼機的PaginatedList類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace NewsApp.Models
{
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int PageSize { get; private set; }
public int TotalCount { get; private set; }
public int TotalPages { get; private set; }
public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
PageSize = pageSize;
TotalCount = source.Count();
TotalPages = (int)Math.Ceiling(TotalCount/(double)PageSize);
this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize));
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 0);
}
}
public bool HasNextPage
{
get
{
return (PageIndex + 1 < TotalPages);
}
}
}
注:我不希望使用任何第三方的組件,如MVCContrib等,因爲這是一所大學的分配,從而會破壞目的。
現在分頁工作正常,但是當我進行搜索時, /?query = test我希望能夠頁面結果,此刻他們迷路了:/
謝謝。
剛剛回答了類似的問題:http://stackoverflow.com/questions/4659978/asp-net-mvc-pagination-using-take-and-skip/4662573#4662573 – Omu 2011-01-11 21:25:57
任何更新謝謝你。 – Cameron 2011-01-11 22:01:32