我在我的MVC4应用程序中使用jQuery数据表(http://www.datatables.net),正如你可能知道这个表允许服务器端处理。我将在与多个控制器绑定的多个视图中使用该表,所以我想实现一种通用的方式来对文件,排序和页面数据进行编排,而无需为每个控制器编写一个方法。如果我这样做,他们看起来都一样,但他们会针对数据库中的不同实体,并对不同的列进行文本过滤和排序。在这里我有什么做的今天:使用实体框架动态过滤,排序和分页通用列表
public virtual ActionResult AjaxHandler(jQueryDataTableParamModel param)
{
var myProducts = _productRepository.Products;
IEnumerable<Product> filteredProducts = myProducts;
// Filtering
if (!string.IsNullOrEmpty(param.sSearch))
{
var searchTermLower = param.sSearch.Trim().ToLower();
filteredProducts = filteredProducts
.Where(c => c.Title.Contains(param.sSearch)
||
c.Manufacturer.ManufacturerName.ToLower().Contains(searchTermLower)
||
c.Category.CategoryTitle.ToLower().Contains(searchTermLower)
||
c.Size.Title.ToLower().Contains(searchTermLower)
||
c.Price.ToString("C").Contains(searchTermLower));
}
// Sorting
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortDirection = Request["sSortDir_0"];
if (sortColumnIndex == 0)
{
filteredProducts = sortDirection == "asc" ? filteredProducts.OrderBy(x => x.CreatedDate) : filteredProducts.OrderByDescending(x => x.CreatedDate);
}
else if (sortColumnIndex == 1)
{
filteredProducts = sortDirection == "asc" ? filteredProducts.OrderBy(x => x.Title) : filteredProducts.OrderByDescending(x => x.Title);
}
else if (sortColumnIndex == 2)
{
filteredProducts = sortDirection == "asc" ? filteredProducts.OrderBy(x => x.Manufacturer.ManufacturerName) : filteredProducts.OrderByDescending(x => x.Manufacturer.ManufacturerName);
}
else if (sortColumnIndex == 3)
{
filteredProducts = sortDirection == "asc" ? filteredProducts.OrderBy(x => x.Size.Title) : filteredProducts.OrderByDescending(x => x.Size.Title);
}
else if (sortColumnIndex == 4)
{
filteredProducts = sortDirection == "asc" ? filteredProducts.OrderBy(x => x.Category.CategoryTitle) : filteredProducts.OrderByDescending(x => x.Category.CategoryTitle);
}
else if (sortColumnIndex == 4)
{
filteredProducts = sortDirection == "asc" ? filteredProducts.OrderBy(x => x.Price) : filteredProducts.OrderByDescending(x => x.Price);
}
// Paging
var displayedProducts = filteredProducts.Skip(param.iDisplayStart).Take(param.iDisplayLength);
var result = from c in displayedProducts
select new[] { c.ProductId.ToString(CultureInfo.InvariantCulture), c.CreatedDate.ToString("G"), c.Title, c.Manufacturer.ManufacturerName, c.Size.Title, c.Category.CategoryTitle, c.Price.ToString("C") };
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = myProducts.Count(),
iTotalDisplayRecords = filteredProducts.Count(),
aaData = result
}, JsonRequestBehavior.AllowGet);
}
我试了几个东西,使其中的这个一般没有完全工作 - 有些是因为我对所有列等其他原因筛选事实。我希望有一个更好的方法来做到这一点,所以我可以传递列或函数来选择列,并使其工作。
你是在一个IEnumerable从您的存储库这样做,这将是存储库中更好。当我这样做时,我使用dapper http://code.google.com/p/dapper-dot-net/用于大型表格,而客户端筛选用于较小的表格,因为EF查询可能会变得很大而且复杂类型的东西。 – 2013-02-24 19:40:42
我确实将一个存储库(DdContext)列表作为IEnumerable传递,以便任何控制器都可以使用它。 – Mensur 2013-02-26 00:49:16