MvcPaging爲我工作。我遵循了這些例子。
在我加入page屬性過濾器視圖模型:
public class FilterViewModel
{
public int? Page { get; set; }
public string UserName { get; set; }
public int? TownId { get; set; }
[Display(Name = "Gender:")]
public bool? IsMale { get; set; }
[Display(Name = "Interests:")]
public int[] InterestsIds { get; set; }
...
}
然後創建一個視圖模型保持IPagedList搜索結果項和過濾選項太:
public class CurrentFilterViewModel
{
//keeps the search result items
public IPagedList<ProfileViewModel> Profiles { get; set; }
public string UserName { get; set; }
public string LastName { get; set; }
public int? TownId { get; set; }
public bool? IsMale { get; set; }
public int[] InterestsIds { get; set; }
...
}
在操作中,我將搜索結果項目和過濾器屬性值傳遞給當前模型屬性
[HttpPost]
public ActionResult FilterProfiles(FilterViewModel filter)
{
var filteredProfilesModel = new CurrentFilterViewModel();
filteredProfilesModel.UserName = filter.UserName ?? null;
filteredProfilesModel.TownId = filter.TownId ?? null;
filteredProfilesModel.IsMale = filter.IsMale ?? null;
filteredProfilesModel.InterestsIds = filter.InterestsIds ?? new int[0];
filteredProfilesModel.MusicGenresIds = filter.MusicGenresIds ?? new int[0];
int DefaultPageSize = 3;
int currentPageIndex = filter.Page.HasValue ? filter.Page.Value - 1 : 0;
filteredProfilesModel.Profiles =
// ... gets the responded items from the database ...
.ToPagedList(currentPageIndex, DefaultPageSize);
return this.PartialView("_FilterProfilesPartial", filteredProfilesModel);
}
至少,在我用ajax放置的局部視圖中,我放置了分頁:將過濾器參數值設置爲當前模型對應的屬性值。使用AddRouteValueFor設置集合參數(我使用數組來保存多個選定項目的id-s)。
@using MvcPaging;
@using System.Linq;
@model Project.Web.ViewModels.CurrentFilterViewModel
<div class="pager">
@Html.Pager(Model.Profiles.PageSize, Model.Profiles.PageNumber, Model.Profiles.TotalItemCount,
new AjaxOptions
{
UpdateTargetId = "profiles",
HttpMethod = "POST"
}).Options(o => o
.Action("FilterProfiles")
.AddRouteValueFor(m => m.InterestsIds)
.AddRouteValue("UserName", Model.FirstName)
.AddRouteValue("TownId", Model.TownId)
.AddRouteValue("IsMale", Model.IsMale)
)
</div>
此解決方案適用於我。我不確定它是否非常優雅。也許有更好的一個。