我遵循了这个tutorial并尝试在我的MVC应用程序中实现排序,过滤和分页。一般来说它没关系 - 它有效,但我不喜欢这样做的代码 - 它很可怕,有问题且复杂。
这是我的模特:
public class ProductOccurence
{
[Key]
public int ProductOccurenceId { get; set; }
public int ProductId { get; set; }
public int ShopId { get; set; }
public decimal ProductPrice { get; set; }
public DateTime ProductBuyDate { get; set; }
public bool IsPromotional { get; set; }
public virtual Product Product { get; set; }
public virtual Shop Shop { get; set; }
}
和ProductSearchModel类(仅用于搜索字段的ViewModel):
public class ProductOccurenceSearchModel
{
public string Description { get; set; }
public string ShopName { get; set; }
public decimal? PriceFrom { get; set; }
public decimal? PriceTo { get; set; }
public DateTime? BuyDateFrom { get; set; }
public DateTime? BuyDateTo { get; set; }
public bool? IsPromotional { get; set; }
}
还声明控制器功能:
public ViewResult Index(string sortOrder, ProductOccurenceSearchModel searchModel, string currentFilterDescription, string currentFilterShopName, decimal? currentFilterPriceFrom, decimal? currentFilterPriceTo, DateTime? currentFilterBuyDateFrom, DateTime? currentFilterBuyDateTo, bool? currentFilterIsPromotional, int? page)
正如您所看到的,有很多变量 - 我还需要为每个字段单独使用ViewBag。在每个地方我都需要参考每个变量,什么是不优雅的,难以理解的 - 并且会产生不必要的冗余代码。
在我看来,它看起来像这样:
排序列的链接:
@Html.ActionLink("ID", "Index", new
{
sortOrder = ViewBag.IDSortParm,
currentFilterDescription = ViewBag.CurrentFilterDescription,
currentFilterShopName = ViewBag.CurrentFilterShopName,
currentFilterPriceFrom = ViewBag.CurrentFilterPriceFrom,
currentFilterPriceTo = ViewBag.CurrentFilterPriceTo,
currentFilterBuyDateFrom = ViewBag.CurrentFilterBuyDateFrom,
currentFilterBuyDateTo = ViewBag.CurrentFilterBuyDateTo,
currentFilterIsPromotional = ViewBag.CurrentFilterIsPromotional
})
和PagedList助手:
@Html.PagedListPager(Model.ProductOccurences, page => Url.Action("Index", new
{
page,
sortOrder = ViewBag.CurrentSort,
currentFilterDescription = ViewBag.CurrentFilterDescription,
currentFilterShopName = ViewBag.CurrentFilterShopName,
currentFilterPriceFrom = ViewBag.CurrentFilterPriceFrom,
currentFilterPriceTo = ViewBag.CurrentFilterPriceTo,
currentFilterBuyDateFrom = ViewBag.CurrentFilterBuyDateFrom,
currentFilterBuyDateTo = ViewBag.CurrentFilterBuyDateTo,
currentFilterIsPromotional = ViewBag.CurrentFilterIsPromotional
}))
这需要在分页和排序时存储结果(参数由URL传输)。 我正在寻找解决方案,我阅读了教程,但从未找到适合许多搜索领域的好解决方案(仅限一两个)。 我怎样才能让它简单干净?例如,通过传输一个对象中的所有值或类似的东西。提前谢谢!