Giter VIP home page Giter VIP logo

datatables.aspnetcore.mvc's Introduction

DataTables.AspnetCore.Mvc

The DataTables.AspnetCore.Mvc provides htmlHelper wrapper for jquery datatables.

NUGET

The easiest way to install is by using NuGet. The current version is writing in netstandard2.0

HowTo

Refer to the official dataTables.net documentation for details on options.

Dependencies

DataTables has only one library dependency jQuery

Add a link on datatables css and javascript files on your page

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/b-1.4.2/b-html5-1.4.2/b-print-1.4.2/sl-1.2.3/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/b-1.4.2/b-html5-1.4.2/b-print-1.4.2/sl-1.2.3/datatables.min.js"></script>

Note that additional packages can be required for extensions.

Add a using on the library in the _ViewImports.cshtml file.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using DataTables.AspNetCore.Mvc

Basic initialisation

The easy way to use it with your own tables is to call the htmlHelper with our id table.

@(Html.Ext().Grid<dynamic>().Name("example"))

You can customize the table css class with the ClassName method

@(Html.Ext().Grid<dynamic>().Name("example")).ClassName("dataTable responsive")

Layout and columns definition can be set with Dom and ColumnDefs method

     @(Html.Ext().Grid<dynamic>().Name("example2")
            .Dom("B<\"clear\">lfrtip")
            .ColumnDefs(c =>
            {
                c.TargetAll().Searchable(false);
                // Column 1 gives order for column 0
                c.Targets(0).OrderData(1);
            })
            .PagingType(PagingType.Full_numbers)
     )

Datasource

External datasource can be set with Datasource method. The datasource option use ajax method to define the source url.

        @(Html.Ext().Grid<dynamic>().Name("example")
            .DataSource(c => 
                c.Ajax().Url("/data/arrays.json").Method("GET")
            )
        )

If json source didn't match your header table it's required to define your columns as explain here

This sample map the columns with the json properties : name, position and office.

        @(Html.Ext().Grid<dynamic>().Name("example")
            .DataSource(c => 
                c.Ajax().Url("/data/arrays.json").Method("GET")
            )
            .Columns(cols =>
            {
                cols.Add().Data("name");
                cols.Add().Data("position");
                cols.Add().Data("office");
            })
        )

ServerSide

When dealing with thousands of data rows it can be helpfull to use the serverside configuration.

The following example map the datasource with a web api. Columns are defined regarding the Product properties class. By default the datasource mapping is based on JsonProperty attribute of property. If none is defined the property name is used. Use the Data method to modify the mapping. Javascript scripts can be added to modify the render of column.

        @(Html.Ext().Grid<Product>().Name("example").RowId("id")
            .Columns(cols =>
            {
                cols.Add(c => c.Name).Title("Name");
                cols.Add(c => c.Office).Title("Office");
                cols.Add(c => c.Position).Title("Position");
                cols.Add(c => c.Salary).Visible(false).Title("Salary");
                cols.Add(c => c.Created).Title("Date");
                cols.Add(c => c.Id).Data("id").Title("").Render(() => "onRender").Click("onClick");
            })
            .ServerSide(true)
            .DataSource(c =>
                c.Ajax().Url("/api/value").Method("GET")
            )
        )
        
        <script>
        function onRender(data, type, row, meta) {
            return '<button type="button" data-type="view" class="btn btn-sm btn-default"><i class="fa fa-lg fa-fw fa-search"></i></button> <button type="button" data-type="remove" class="btn btn-sm btn-danger"><i class="fa fa-lg fa-fw fa-trash"></i></button>';
        }

        function onClick(e) {
          if (e.data.type == 'remove') {
            console.log('remove clicked');
          } else if (e.data.type == 'view') {
            console.log('view clicked');
          }
        }
        </script>
    public class Product
    { 
        // JsonProperty not defined
        public int Id { get; set; }

        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "position")]
        public string Position { get; set; }

        [JsonProperty(PropertyName = "office")]
        public string Office { get; set; }

        [JsonProperty(PropertyName = "salary")]
        public string Salary { get; set; }

        [JsonProperty(PropertyName = "created")]
        public DateTime Created { get; set; }
    }

From server side, the request is processing using the helper class DataTableRequest and extension ToDataTablesResponse on collection.

        [HttpGet()]
        [Route("api/value")]
        public IActionResult Get([DataTablesRequest] DataTablesRequest dataRequest)
        {
            IEnumerable<Product> products = Products.GetProducts();
            int recordsTotal = products.Count();
            int recordsFilterd = recordsTotal;

            if (!string.IsNullOrEmpty(dataRequest.Search?.Value))
            {
                products = products.Where(e => e.Name.Contains(dataRequest.Search.Value));
                recordsFilterd = products.Count();
            }
            products = products.Skip(dataRequest.Start).Take(dataRequest.Length);

            return Json(products
                .Select(e => new
                {
                    Id = e.Id,
                    Name = e.Name,
                    Created = e.Created,
                    Salary = e.Salary,
                    Position = e.Position,
                    Office = e.Office
                })
                .ToDataTablesResponse(dataRequest, recordsTotal, recordsFilterd));
       }

Events

Events are catch from client side with the Events method

        @(Html.Ext().Grid<dynamic>().Name("example")
            .Select(s => {})
            .Events(e => { e.Select("onSelected").Deselect("onDeselected"); })
        )
        
        <script type="text/javascript">
          function onSelected(e, dt, type, i) {
              console.log("select " + type);
          }

          function onDeselected(e, dt, type, i) {
              console.log("deselect " + type);
          }
      </script>

Extensions

The current library supports buttons and select extensions. Following sample enable the Select extension and catch select/deselect events

        @(Html.Ext().Grid<dynamic>().Name("example")
            .ColumnDefs(c =>
            {
                c.Targets(0).Orderable(false).ClassName("select-checkbox");
            })
            .Select(s => {
                s.Blurable(true).Info(true);
            })
            .Events(e =>
            {
                e.Select("onSelected").Deselect("onDeselected");
            }
            )
        )

Sample of table

    <table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009/01/12</td>
                <td>$86,000</td>
            </tr>
        </tbody>
    </table>

External links:

DataTables.Net

datatables.aspnetcore.mvc's People

Contributors

beffyman avatar lzorglub avatar teghoz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

datatables.aspnetcore.mvc's Issues

Support for jquery defer loading

Thank you for this great contribution.
When jquery loading is deferred, as of now we get error $ is not defined and datatable initialization fails. It would be great if you could add support for this.

Binding to additional parameters.

Is there a way to bind to additional parameters, or how would one go about implementing that along with this library?

According to the documentation for datatables I have sent the following parameters up to the controller:

                ajax: {
                    method: 'post',
                    url: './api/audits',
                    data: function (data) {
                        data.dateFrom = $('#dateFrom').val();
                        data.dateTo = $('#dateTo').val();
                    }
                }

Any way to bind to these two additional parameters, or should I just pull directly from request?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.