Are you the publisher? Claim or contact us about this channel

Embed this content in your HTML


Report adult content:

click to rate:

Account: (login)

More Channels


Channel Catalog

Channel Description:

Recent Discussions — DataTables forums

older | 1 | .... | 2287 | 2288 | (Page 2289) | 2290 | 2291 | .... | 2326 | newer

    0 0

    I have seen people asking a few times how to use datatables serverside with MVC and EF with paging sorting and searching etc. I had some code lying around so I thought its time to give back and share a simple implementation.

    Unfortunately I don't have time right now to create a sample solution for download so I just hacked out the code and pasted it in here as a guide.

    For the dynamic searching (where clause) you will need linqkit for the predicate building.

    First map the datatable inbound JSON requests to classes

    Start - JSon class sent from Datatables
    public class DataTableAjaxPostModel
        // properties are not capital due to json mapping
        public int draw { get; set; }
        public int start { get; set; }
        public int length { get; set; }
        public List<Column> columns { get; set; }
        public Search search { get; set; }
        public List<Order> order { get; set; }
    public class Column
        public string data { get; set; }
        public string name { get; set; }
        public bool searchable { get; set; }
        public bool orderable { get; set; }
        public Search search { get; set; }
    public class Search
        public string value { get; set; }
        public string regex { get; set; }
    public class Order
        public int column { get; set; }
        public string dir { get; set; }
    /// End- JSon class sent from Datatables

    Next implement your action in a standard controller (note in this example we are not using a Web-API controller)

    This method just grabs the data sent from the table and calls YourCustomSearchFunc() before returning a formatted json obj for Datatables to consume.

    public JsonResult CustomServerSideSearchAction(DataTableAjaxPostModel model)
        // action inside a standard controller
        int filteredResultsCount;
        int totalResultsCount;
        var res = YourCustomSearchFunc(model, out filteredResultsCount, out totalResultsCount);
        var result = new List<YourCustomSearchClass>(res.Count);
        foreach (var s in res)
            // simple remapping adding extra info to found dataset
            result.Add(new YourCustomSearchClass
                EmployerId = User.ClaimsUserId(),
                Id = s.Id,
                Pin = s.Pin,
                Firstname = s.Firstname,
                Lastname = s.Lastname,
                RegistrationStatusId = DoSomethingToGetIt(s.Id),
                Address3 = s.Address3,
                Address4 = s.Address4
        return Json(new
            // this is what datatables wants sending back
            draw = model.draw,
            recordsTotal = totalResultsCount,
            recordsFiltered = filteredResultsCount,
            data = result

    YourCustomSearchFunc() is very simple it just sets up the sort column and sort direction before calling the database search functionality. In this example we are only allowing sorting on a single column but you could easily implement multi column sorting.

    public IList<YourCustomSearchClass> YourCustomSearchFunc(DataTableAjaxPostModel model, out int filteredResultsCount, out int totalResultsCount)
        var searchBy = ( != null) ? : null;
        var take = model.length;
        var skip = model.start;
        string sortBy = "";
        bool sortDir = true;
        if (model.order != null)
            // in this example we just default sort on the 1st column 
            sortBy = model.columns[model.order[0].column].data;
            sortDir = model.order[0].dir.ToLower() == "asc";
        // search the dbase taking into consideration table sorting and paging
        var result = GetDataFromDbase(searchBy, take, skip, sortBy, sortDir, out filteredResultsCount, out totalResultsCount);
        if (result == null)
            // empty collection...
            return new List<YourCustomSearchClass>();
        return result;

    This is the main meat of the functionality. In it we simply select from the dbase but instead of using a fixed where clause we use a dynamic expression built using the wonderful LinqKit to generate the predicate.

    Additionally we use Take and Skip to allow us to page through the data. Notice we use the where clause twice. Once to select the data and pick a page, the second time to count how many items we could have returned.

    public List<YourCustomSearchClass> GetDataFromDbase(string searchBy, int take, int skip, string sortBy, bool sortDir, out int filteredResultsCount, out int totalResultsCount)
        // the example datatable used is not supporting multi column ordering 
        // so we only need get the column order from the first column passed to us.         
        var whereClause = BuildDynamicWhereClause(Db, searchBy);
        if (String.IsNullOrEmpty(searchBy))
            // if we have an empty search then just order the results by Id ascending
            sortBy = "Id";
            sortDir = true;
        var result = Db.DatabaseTableEntity
                       .Select(m => new YourCustomSearchClass
                           Id = m.Id,
                           Firstname = m.Firstname,
                           Lastname = m.Lastname,
                           Address1 = m.Address1,
                           Address2 = m.Address2,
                           Address3 = m.Address3,
                           Address4 = m.Address4,
                           Phone = m.Phone,                      
                           Postcode = m.Postcode,                      
                       .OrderBy(sortBy, sortDir) // have to give a default order when skipping .. so use the PK
        // now just get the count of items (without the skip and take) - eg how many could be returned with filtering
        filteredResultsCount = Db.DatabaseTableEntity.AsExpandable().Where(whereClause).Count();
        totalResultsCount = Db.DatabaseTableEntity.Count();
        return result;

    Here is the predicate builder function that just plugs in a where clause dynamically. You will need to install (nugget) in linqkit for this.

    In this example I am searching where the searchterm appears in either the firstname or lastname

    private Expression<Func<DatabaseTableMappedClass, bool>> BuildDynamicWhereClause(DBEntities entities, string searchValue)
        // simple method to dynamically plugin a where clause 
        var predicate = PredicateBuilder.New<DatabaseTableMappedClass>(true); // true -where(true) return all
        if (String.IsNullOrWhiteSpace(searchValue) == false)
            // as we only have 2 cols allow the user type in name 'firstname lastname' then use the list to search the first and last name of dbase
            var searchTerms = searchValue.Split(' ').ToList().ConvertAll(x => x.ToLower());
            predicate = predicate.Or(s => searchTerms.Any(srch => s.Firstname.ToLower().Contains(srch)));
            predicate = predicate.Or(s => searchTerms.Any(srch => s.Lastname.ToLower().Contains(srch)));
        return predicate;

    The only left to show is the datatable itself

    var table = $('#SearchResultTable').DataTable({
        "proccessing": true,
        "serverSide": true,
        "ajax": {
            url: "@Url.Action("CustomServerSideSearchAction", "Home")",
            type: 'POST'
        "language": {
            "search": "",
            "searchPlaceholder": "Search..."
       "columns": [
            { "data": "Firstname" },
            { "data": "Lastname" }

    Hope this helps

    0 0

    I have a first_name field and a last_name field and I would like to concatenate them into a full_name field automatically and save the full_name into the database. I could also just display the full_name in the datatable. That would work also. I have been reading about preSubmit, render, setFormatter but I'm not having any luck getting those to work. What is the best way to do this and can someone show an example code snippet or two?

    0 0
  • 12/08/18--14:29: parent child datatables
  • Hi,

    Its been a while, I am back again. trying to get parent and child datables on click of parent row.

    here is my code

    `<!DOCTYPE html>
    <link rel="stylesheet" type="text/css" href=""/>
    <script type="text/javascript" src=""></script>
    <script src=""></script>
        <meta charset=utf-8 />
        <title>DataTables -  Parent and Child</title>
        <div class="container">
          <table id="example" class="display nowrap" width="100%">
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>First Name</th>
                    <th>Last Name</th>
          <table id="child" class="LogDetails"> 
                    <th>Loged Date</th>
                    <th>Loged Out Time</th>

    my javascript

    $(document).ready(function() {
        var table = $('#example').DataTable( {
            "columns": [
                {   "orderable":      true,
                    "data":           null,
                    "defaultContent": ''
                { "data": "A" },
                { "data": "B" },
                { "data": "C" },
                { "data": "D" }
            "order": [[1, 'asc']]
        } );
        // Add event listener for opening and closing details
        $('#example tbody').on( 'click', 'button', function () {
        var data = table.row( $(this).parents('tr') ).data();
    } );
    } );

    Anyone around to help, so i can use ssp class to retrieve data from my sql database please?


    Just from the text file the child data?_

    0 0

    Hi. I have a table populated with AJAX data that has a date column. I'd like to group the data in the table by month name, so I created a column that I setup as follows:

                data: "startDate",
                visible: false,
                render: function (data) {
                    return moment(data).format("MMMM");

    My problem is that I can't see to figure out how to get rowGroup to group by the month name. When I try setting rowGroup to true (with the above column as my first column) or set it to the specific column number, nothing happens. I assume this is because I am using AJAX data. Is there a way to get this to work other than adding "month" to the database?

    0 0

    Fix Header coming on other tables:

    Fix header coming on other Views:

    My Directive:

              angular.module('datatable.directive', [])
              .directive('datatable', function ($compile) {
                return {
            scope: {
                dtData: '=',
                dtColumns: '=',
                dtSort: '=',
                dtDirection: '=',
                dtFilter: '=',
                dtPagination: '=',
                dtFixed: '='
            transclude: true,
            controller: function($scope, $location) {
                $scope.navigateToListing = function(id) {
                    $location.path('/seller/listing/management/' + id);
            link: function (scope, elem, attrs, ctrl) {
                var pagination = true;
                if( attrs.dtPagination == 'no' ) {
                    pagination = false;
                $.fn.dataTable.ext.errMode = 'throw';
                    bFilter: true,
                    data: scope.dtData,
                    columns: scope.dtColumns,
                    language: {
                        search: '',
                        searchPlaceholder: 'Search'
                    createdRow: function ( row, data, index ) {
                        // $(row).attr('ng-class', '{selected: selectedRow['']}');
                    initComplete: function() {
                        var thead = elem.find('thead tr');
                        var ix = 0;
                        var columns = this.api().init().columns;
                        this.api().columns().every( function () {
                            if(!columns[ix].uniqueFilter) {
                            var column = this;
                            var th = elem.find('thead tr th').eq(ix);
                            var title = columns[ix].sTitle;
                            var select = $('<select class="form-control input-sm"><option value="">' + title.toUpperCase() + '</option></select>');
                            select.on( 'change', function (ev) {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    .search( val ? '^'+val+'$' : '', true, false )
                            } );
                            select.on('click', function(ev) {
                   function ( d, j ) {
                                select.append( '<option value="'+d+'">'+d+'</option>' );
                            } );
                        } );
                        if(scope.dtFilter) {
                            var table_id = $(this).attr('id');
                            $("#" + table_id + "_filter").appendTo("#" + scope.dtFilter);
                            $("#" + table_id + "_filter").find("input").first().removeClass("input-sm");
                    lengthChange: false,
                    order: scope.dtSort == 'NONE' ? []: [[scope.dtSort || 0, scope.dtDirection || 'desc']],
                    paging: pagination,
                    fixedHeader: scope.dtFixed == true ? true : false

    My Controller:

         angular.module('reports.controller', [])
            .controller('ReportsCtrl', ['API_URL', '$scope', '$route', '$location', 'SessionSvc', 'ReportSvc', '$analytics', 
            'CacheFactory', 'ngDialog', '$filter',
            function (API_URL, $scope, $route, $location, SessionSvc, ReportSvc, $analytics, CacheFactory, ngDialog, $filter) {
            $scope.API_URL = API_URL;
            $scope.state = {};
            $scope.state.dtFilterField = 'filter_target';
            $scope.loading = false;
            ReportSvc.getReports().then(function (resp) {
                var reports_var =;
                $scope.reports = _.groupBy(reports_var, 'category');
            $scope.getReport = function (rpt_key, rpt_name) {
                $scope.state.selectedReport = rpt_name;
                $scope.state.values = {};
                $scope.loading = true;
                $scope.error = "";
                ReportSvc.get(rpt_key).then(function (resp) {
                    $scope.loading = false;
                    $scope.state.reportName =;
                    $scope.state.reportKey =;
                    if( ) {
                        $scope.error =;
                    else {
                        $scope.state.reportDesc =;
                        $scope.state.colNames =;
                        $scope.state.values =;
                        var colSpec = [];
                        _.each($scope.state.colNames, function (colName) {
                            var spec = {'title': colName.replace(/_/g, ' ')};
                            if (reportParams[rpt_key] && reportParams[rpt_key]['colSpec'][colName]) {
                                angular.extend(spec, reportParams[rpt_key]['colSpec'][colName])
                        $scope.state.dtColumns = colSpec;
                }, function(resp) {
                    alert("Error running report.")
            var reportParams = {};
            reportParams['TEST'] = {
                'colSpec': {
                    'company_name': {'uniqueFilter': true},
                    'listing_id': {
                        'render': function (data, type, full, meta) {
                            return '<a ng-href="/listing_details/' + data + '">' + data + '</a>';
            var sessionCache = CacheFactory.get('sessionCache');
            $scope.$on('$routeChangeStart', function (next, current) {
                sessionCache.put('reportContext', $scope.state)
            if (sessionCache.get('reportContext')) {
                $scope.state = sessionCache.get('reportContext');

    My Html:

                    <ul class="dropdown-menu">
                         <li ng-repeat="report in names">
                              <a href ng-click="getReport(report.key,">{{ }}</a>
                   <table style="width:100%" class="table table-bordered" dt-fixed="true" dt-sort="'NONE'" dt-direction="desc" datatable dt-data="state.values" dt-filter="state.dtFilterField"
           dt-columns="state.dtColumns" dt-pagination="no">

    0 0

    I have added child rows from the example . Now I want to add responsive to the table. I have a problem that when I show the child row, the table is way to wide even for the container. I thought maybe there was some configuration problem but notice that when I remove "nowrap" from the table it is fine. But then the responsive does not work. When I have table class="display responsive nowrap" any long text in a TD in child row breaks the width. Is there a way to fix this?
    Here is closed:
    Here it is opened:

    0 0

    Some of my rows have groupings (in my case they are like child entries of the parent), but some dont. I would like those that do have row groupings to be grouped, but those that dont, dont. Just have them as normal rows ungrouped, and be ordered within the same sorting as the groups. So I would only see the groupings for those with child entries.

    So it would be like this:

    Element 1
    - Element 1 Child 1
    - Element 1 Child 2
    - Element 1 Child 3
    Element 2
    Element 3
    - Element 3 Child 1
    - Element 3 Child 2


    0 0
  • 12/12/18--14:11: Column Troubles.
  • Having a bit of trouble working through a complex datatable, and I'm struggling to get the column display that I want.

    Some background:
    * The columns.visibility() function is much too slow, and it is causing other issues that I would resolve if the performance wasn't so bad.
    * To hide/show columns I'm setting a class to 'd-none', or style to 'display: none' on the TH and TD. This is working OK, and speed is much better than column.visibility()
    * At the moment, the hidden columns and headers hide; but the table doesn't flow to fill the space (I've skipped over table.columns.adjust().draw() for performance reasons; and because it forces me to put 100% width on the table, which breaks Fixed Header early in the game).
    * The main problem is that the Fixed Header fills the space as I would have expected the main table to do.

    I can stop this behavior by shorting my ghost TH row by one TH (the collapsed row of TH in the very first row the thead to resolve complex header issues). So, if my table has 10 columns and I put in 9 TH everything works OK in Firefox, but I have a slight alignment issue in Chrome and Edge. If I fix it, and go 10 to 10, then my headers in the Fixed Header expand to fill the space.

    I've tried setting the max-width, width, and min-width properties on the Fixed Header TH. I've tried removing table-layout: fixed from the Fixed Header.

    If I could get Fixed Header to show an exact copy of the actual table header, I would be able to call it good for now.

    Any ideas?

    0 0

    I put together this example of using the HTML5 drag and drop API to move rows between two Datatables. Its an interesting API and doesn't require additional JS libraries for drag and drop. It was a good learning experience to build this example. Hope it helps others how want to drag and drop between tables.,css,js,output


    0 0

    Hi! I have a table where a column has different row values like:
    8.80 € - 20.23 €
    1.27 €
    6.50 €

    Problem is the sorting. It always sorts it asc and desc just like in the database. :disappointed: The column in the database is varchar(24) for the obvious reason - different units. Column is #9. I have declared columndefs like so:


    How should I make it sort properly? Neither declaring html-num, nor html-num-fmt instead of num-fmt helped because server-side processing is used. I want to see that 16.25% is greater than 1.95 € for example. Could it be changed to show % on top of € values always, too?

    0 0

    Here is a minimal example, note the addition of a multi column header:

    If you expand these rows to take up enough space to add a vertical scrollbar to the page, and scroll down, FixedHeader does not calculate the proper column widths and the column headers resize as a result.

    How can I fix this?

    I am also having a problem where the fixedheader width is incorrect if the datatable initially takes up less than 100% of the width of the page and a scrollbar is then added, but I've solved that for now by calling table.fixedHeader.adjust() on a fast enough timer that it doesn't really matter to the end user. Is there a correct solution?


    0 0
  • 12/12/18--20:02: how to get main value
  • halo,

    im sorry if its basic but im already waste time for this
    how i can get main value from this return?
    apreciate for the help

    thos.target_store.elm.tabled.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
    var rendered = this.cells( rowLoop, '' ).render( 'display' );
    // console.log(rendered)
    } );

    0 0

    I recently joined this forum, and got my first question successfully answered (yay, community!). But I never got any emails, either about creating the account in the first place or when I got replies to my question. No, there is nothing relevant in my Junk Folder. Here is a screenshot of my Notification Preferences:

    I don't know what a "wall" is, but I think the type I should have gotten is "when people comment on my discussions". I also bookmarked my discussion, but that didn't help.

    0 0

    hi,i have a question about datatables,like the example Child rows,but i need the child row show up another table!The second table like the first also use ajax to load data,now i try the way like example but i can't work,when i click the row,the child row show up a while then close,i google it whole afternoon but nothing found to solve this problem,can anyone have any ideas or did this before?

    0 0
  • 12/13/18--02:12: Jquery 3x compatibility
  • Hi
    We are using DataTables 1.9.4. Is it compatible with Jquery 3.3.1

    0 0
  • 12/13/18--02:14: Jquery 3x compatibility
  • Hi
    We are using DataTables 1.9.4. Is it compatible with Jquery 3.3.1

    0 0
  • 12/13/18--03:00: Large data file uploads
  • Hello everyone,

    I'm new to datatables and I have been using the 15 day trial to explore the tool's feature sets and so far, I must say I'm very impressed.
    I know image files can be uploaded while creating new row data entires - but I have a particularly important use case that I'm working on that requires large data sets (tens of thousands of rows and several tens of columns) to be uploaded at a go through CSV files at the front end by the end users.

    Can anyone advise me if datatables natively supports this feature?

    Thank you

    0 0

    How to change background color of a row based on a value in column 'C' in Excel export HTML5?

    $('row c[r^="C"]', sheet).each( function () {
    if($(this).text() == 'TOTAL'){
    $(this).attr( 's', '20' );

    This will change the bg color of that cell but how to change the entire row color?

    0 0

    My issue comes from the server-side pagination.
    Once new data has been injected by ajax source, I need to draw again the table to get the reading fixed because I don't use multiple line per cell. So new contents may be shorter then previous, or longer and the overflow goes on the background than the following cell. It's fine for me, so I just need to redraw using a button that act like a kind of refresh for the table structure:
    { text: 'Refresh', action: function () { table.columns.adjust().draw(); } }
    This is just a kind of workaround and it's working, I'm looking for adding this behaviour to the ajax response got from DataTable and I am not able.
    If I handle the fnDrawCallback I got infinite refresh that stucks on my web client page, of course it's not a good solution.
    By the way, a problem of the main workaround is with the pagination because the button that act like a refresh for the structure of the table brings me back to the first page. If I'm reading contents from the n-th page and I just need to "refresh" tha table I don't get refreshed my current view, so actually there is no way to "refresh" structure for pages that are not the first.

    This is my table definition:
    table = $("#" + table_name).DataTable({
    "processing": true,
    "serverSide": true,
    "scrollY": '50vh',
    "scrollX": true,
    "scrollCollapse": true,
    "autoWidth": true,
    "columnDefs": [
    { "targets": "all", "defaultContent": "-" },
    { "targets": [4,5,6], "createdCell": function (td, cellData, rowData, row, col) {
    if ( cellData == 1 ) {
    } else if ( cellData == 0 ) {
    } },
    { "targets": 3, "createdCell": function (td, cellData, rowData, row, col) {
    if ( cellData == 1 ) {
    } }
    "columns": [
    { "data": "foo", "className": 'details-control'},
    { "data": "bar" },
    { "data": "bar" },
    { "data": "RowNum", "orderable": false, "visible": false }
    "ajax": {
    "url": "json/ricerca_bdt_ng.php",
    "method": "POST",
    "data": function (d) {
    d.user = account;
    d.pass = password;
    d.user_ad = account_ad;
    d.pass_ad = password_ad;
    d.device = deviceid; = dbhost;
    d.port = dbport;
    d.db = dbname;
    "language": {
    "lengthMenu": "Display _MENU
    records per page",
    "zeroRecords": "Nothing found - sorry",
    //"info": "Showing page PAGE of PAGES",
    "infoEmpty": "No records available",
    //"infoFiltered": "(filtered from MAX total records)",
    "processing": "

    "searchPlaceholder": "Global"

        // Enable datatables.mark.js highlighting
        "mark": true,
        //"select": true,
        "select": {
            style: 'os',
            items: 'cell'
        "dom": "<'fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix ui-corner-bl ui-corner-br'Blf>rt<'fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix ui-corner-bl ui-corner-br'ip><'clear'>",
        "buttons": [
            { extend: 'excelHtml5', title: exportfile },
            { extend: 'selectedSingle',
              text: 'Copia cella',
              action: function ( e, dt, node, config ) {
                var sdata = table.cell('.selected').data();
            { text: 'Refresh', action: function () { table.columns.adjust().draw(); } }
        /*"fnDrawCallback": function( oSettings ) {
            console.log( 'DataTables has redrawn the table' );
    // fix input placeholder width

    This is part of the css I'm using with the table:
    /* fix table scrolling out his div /
    margin: 0 auto;
    width: 100%;
    clear: both;
    border-collapse: collapse;
    table-layout: fixed;
    word-wrap: break-word;*/
    min-width: 100%;

    th, td { white-space: nowrap; overflow: hidden; }
    /th, td { white-space: normal; }/

    /* dimensionamento tabella /
    th { word-break: normal; }
    td { word-break: break-all; } */

    td.accapo { word-break: normal; }

    div.dataTables_wrapper {
    width: 95%;
    margin: 0 auto;

    div.dataTables_wrapper div.dataTables_processing {
    top: 5%;

    div.row_details {
    width: 950px;
    padding: 20px;

    /* Floating column for labels: 25% width */
    .col-25 {
    float: left;
    width: 25%;
    margin-top: 6px;

    /* Floating column for inputs: 75% width */
    .col-75 {
    float: left;
    width: 75%;
    margin-top: 6px;

    /* Clear floats after the columns */
    .row:after {
    content: "";
    display: table;
    clear: both;

    I'm sorry I am not able to make a working example, I will make treasure of every advice you give me.

    0 0

    ****I try this code but it has a error********

    Editor::->where( function ($q) {
    $q->where( 'id',$limit );
    } )

older | 1 | .... | 2287 | 2288 | (Page 2289) | 2290 | 2291 | .... | 2326 | newer