jQuery Datatable with MVC 5 and Entity Framework

后端 未结 2 2046
盖世英雄少女心
盖世英雄少女心 2021-01-30 19:06

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.

The exam

相关标签:
2条回答
  • 2021-01-30 19:30

    Use EFDatatable

    What is 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

    @(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.

    public JsonResult GetDataResult(DataRequest request)
        {
            DataResult result = context.People.ToDataResult(request);
            return Json(result);
        }
    

    Where can I get it?

    Install EFDatatable from the package manager console:

    PM> Install-Package EFDatatable
    

    Then add datatables.net Javascript and CSS files or links to your project.

    <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>
    
    0 讨论(0)
  • 2021-01-30 19:46

    ------------------------------- 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.

    What's changed so far?

    DataTables.Mvc started over an year ago. It has changed and now it's called DataTables.AspNet. But that's not all.

    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.

    Now we have a modular architecture with Nuget packages to help. You can either reference Core package and implement everything yourself or you can get apropriate packages (Mvc5 or AspNet; WebApi2 is comming soon) with native model binders, one-line registration and a full test suite.

    How to get started?

    Check out samples folder on dev branch (click here). Don't forget to get appropriate Nuget packages. You can find a list of them here.

    ------------------------------- Original answer -------------------------------

    First things first

    You can either use DataTables 1.9, 1.10 with old API or 1.10 with the new 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 GitHub to help with the bindings.

    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:

    1. Global filter/search
    2. Column filter/search
    3. 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);
    }
    
    0 讨论(0)
提交回复
热议问题