ajax 带有 MVC 5 和实体框架的 jQuery 数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22466041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Datatable with MVC 5 and Entity Framework
提问by Kode
I need some guidance on what to put in my controller so that I can use server-side processing with my jQuery datatables. I am using MVC 5 and Entity Framework.
我需要一些关于在我的控制器中放置什么的指导,以便我可以对我的 jQuery 数据表使用服务器端处理。我正在使用 MVC 5 和实体框架。
The example at: http://datatablesmvc.codeplex.com/documentationstates the following:
位于http://datatablesmvc.codeplex.com/documentation的示例说明如下:
public class HomeController : Controller {
[HttpPost]
public ActionResult GetDataTables(DataTable dataTable) {
List<List<string>> table = new List<List<string>>();
//Do something with dataTable and fill table
return new DataTableResult(dataTable, table.Count, table.Count, table);
}
}
But what do I do when I am using LINQ such as this?
但是当我使用这样的 LINQ 时我该怎么办?
public ActionResult Index()
{
var activity = db.Activity.Include(a => a.ActivityType);
return View(activity.ToList());
}
回答by Anderson Matos
------------------------------- Updated answer -------------------------------
------------------------------- 更新答案 ----------------- --------------
Why the update?
为什么更新?
This answer seems to keep getting much attention from SO users and I thought everyone could benefit from a "little" update.
这个答案似乎一直受到 SO 用户的关注,我认为每个人都可以从“小”更新中受益。
What's changed so far?
到目前为止有什么变化?
DataTables.Mvcstarted over an year ago. It has changed and now it's called DataTables.AspNet. But that's not all.
DataTables.Mvc一年多前开始。它已经改变,现在它被称为DataTables.AspNet。但这还不是全部。
At that time, aim was to help with base classes. Problem is that you'd just get a zip and should manually merge all that into your project. Also, there was no binder for models and integration was really boring.
当时,目标是帮助处理基类。问题是您只会得到一个 zip 文件,并且应该手动将所有这些文件合并到您的项目中。此外,模型没有活页夹,集成也很无聊。
Now we have a modular architecture with Nuget packages to help. You can either reference Corepackage and implement everything yourself or you can get apropriate packages (Mvc5or AspNet; WebApi2is comming soon) with native model binders, one-line registration and a full test suite.
现在我们有了一个带有 Nuget 包的模块化架构来提供帮助。您可以参考Core包装和实施一切自己,或者你可以得到apropriate包(Mvc5或AspNet,WebApi2被正在添加很快),与原生模型粘合剂,一种网上报名和一个完整的测试套件。
How to get started?
如何开始?
Check out samplesfolder on devbranch (click here).
Don't forget to get appropriate Nuget packages. You can find a list of them here.
查看分支上的samples文件夹dev(单击此处)。不要忘记获得适当的 Nuget 包。您可以在此处找到它们的列表。
------------------------------- Original answer -------------------------------
------------------------------- 原答案----------------- --------------
First things first
第一件事
You can either use DataTables 1.9, 1.10 with old API or 1.10 with the new API.
您可以将 DataTables 1.9、1.10 与旧 API 或 1.10 与新 API 一起使用。
If you choose the new API (1.10 only) than you'll miss some plugins here and there but you can use DataTables.AspNet on GitHubto help with the bindings.
如果您选择新的 API(仅限 1.10),那么您会在这里和那里错过一些插件,但您可以使用GitHub 上的 DataTables.AspNet来帮助绑定。
If not, you can take a look and change the code to match request variables from other versions (support will be provided later on my project).
如果没有,您可以查看并更改代码以匹配来自其他版本的请求变量(稍后将在我的项目中提供支持)。
The real-deal
真正的交易
Point is that you'll have to handle three items:
重点是你必须处理三个项目:
- Global filter/search
- Column filter/search
- Column sort
- 全局过滤/搜索
- 列过滤/搜索
- 列排序
Gimme some code!
给我一些代码!
That might change from which version and if you're using (or not) my binding class. Consider that you're using it, for the sake of avoiding handling request parameters here, ok?
如果您使用(或不使用)我的绑定类,这可能会从哪个版本发生变化。考虑一下你正在使用它,为了避免在这里处理请求参数,好吗?
So, you can play with something like this:
所以,你可以玩这样的东西:
[HttpPost]
public ActionResult Index([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestParameters)
{
var totalCount = myDbContext.Set<Something>().Count();
var filteredDataSet = myDbContext.Set<Something>().Where(_s => _s.ToLower().Contains(requestParameters.Search.Value));
foreach(var column in requestParameters.Columns.GetFilteredColumns())
{
// Apply individual filters to each column.
// You can try Dynamic Linq to help here or you can use if statements.
// DynamicLinq will be slower but code will be cleaner.
}
var isSorted = false;
IOrderedEnumerable<Something> ordered = null;
foreach(var column in requestParameters.Columns.GetSortedColumns())
{
// If you choose to use Dynamic Linq, you can apply all sorting at once.
// If not, you have to apply each sort manually, as follows.
if (!isSorted)
{
// Apply first sort.
if (column.SortDirection == Column.SortDirection.Ascendant)
ordered.OrderBy(...);
else
ordered.OrderByDescending(...);
isSorted = true;
}
else
{
if (column.SortDirection == Column.SortDirection.Ascendant)
ordered.ThanBy(...);
else
ordered.ThanByDescending(...);
}
}
var pagedData = ordered.Skip(requestParameters.Start).Take(requestParameters.Length);
var dataTablesResult = new DataTablesResult(
requestParameters.Draw,
pagedData,
filteredDataSet.Count(),
totalCount
);
return View(dataTablesResult);
}
回答by Emrah KONDUR
Use EFDatatable
What is EFDatatable?
什么是 EFDatatable?
EFDatatable is a helper to create a grid with Jquery Datatable and provides an extension to retrive data generically from Entity Framework context. It possible to use many datatable.js features with Html helper. It gives serverside or client side options. There's more: Wiki Documentation
EFDatatable 是使用 Jquery 数据表创建网格的助手,并提供扩展以从实体框架上下文中检索数据。可以通过 Html helper 使用许多 datatable.js 功能。它提供服务器端或客户端选项。还有更多:维基文档
@(Html.EF().Datatable<Person>()
.Name("PersonGrid")
.Columns(cols =>
{
cols.Field(a => a.Id).Visible(false);
cols.Field(a => a.Name).Title("First Name").Class("text-danger");
cols.Field(a => a.Age).Title("Age").Searchable(false);
cols.Field(a => a.BirthDate).Title("Birth Date").Format("DD-MMM-Y");
cols.Command(a => a.Id, "onClick", text: "Click").Title("");
})
.Filters(filter =>
{
filter.Add(a => a.Id).GreaterThanOrEqual(1);
})
.URL(Url.Action("GetDataResult"), "POST")
.ServerSide(true)
.Render()
)
With "ToDataResult(request)" extension function, data can get with server side pagination very simply.
使用“ToDataResult(request)”扩展函数,可以非常简单地通过服务器端分页获取数据。
public JsonResult GetDataResult(DataRequest request)
{
DataResult result = context.People.ToDataResult(request);
return Json(result);
}
Where can I get it?
我在哪里可以得到它?
Install EFDatatablefrom the package manager console:
从包管理器控制台安装EFDatatable:
PM> Install-Package EFDatatable
Then add datatables.netJavascript and CSS files or links to your project.
然后将datatables.netJavascript 和 CSS 文件或链接添加到您的项目。
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>

