32

Scenario

I am using (@version 1.9.4) for the first time to display data to the user. I succeed in retrieving the data via ajax and in binding them to the datatable.

Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.

In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.

Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:

Requested unknown parameter '5' from data source for row 0

Question

How to set custom columns? How to fill their content with HTML?


Here is my actual config.

HTML

<table id="tableCities">
    <thead>
        <tr>
            <th>country</th>
            <th>zip</th>
            <th>city</th>
            <th>district code</th>
            <th>district description</th>
            <th>actions</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

Javascript

$('#tableCities').dataTable({
    "bPaginate": true,
    "bLengthChange": false,
    "bFilter": true,
    "bSort": true,
    "bInfo": false,
    "bAutoWidth": true
    , "bJQueryUI": true
    , "bProcessing": true
    , "bServerSide": true
    , "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});

Sample Json result

{
    "aaData":
    [
        [
            "IT",
            "10030",
            "VILLAREGGIA",
            "TO",
            "Torino"
        ],
        [
            "IT",
            "10030",
            "VISCHE",
            "TO",
            "Torino"
        ]
    ],
    "iTotalRecords": 2,
    "iTotalDisplayRecords": 2,
    "iDisplayStart": 0,
    "iDisplayLength": 2
}

Edit

Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.

/* inside datatable initialization */
, "aoColumnDefs": [
   {
        "aTargets": [5],
        "mData": null,
        "mRender": function (data, type, full) {
            return '<a href="#" onclick="alert(\''+ full[0] +'\');">Process</a>';
        }
    }
 ]
Community
  • 1
  • 1
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
  • 1
    it's works for me, +1 for additional html link/button on each row complete with 'get the row id value'. – bungdito Jul 17 '13 at 01:45

4 Answers4

33

You can define your columns in a different way like this

"aoColumns": [
        null,
        null,
        null,
        null,
        null,
        { "mData": null }
    ]

or this

"aoColumnDefs":[
    {
        "aTargets":[5],
        "mData": null
    }
]

Here some docs Columns

Take a look at this DataTables AJAX source example - null data source for a column

Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.

Another solution/workaround could be adding that '5' parameter...

For example adding extra "" to each row

like this:

    [
        "IT",
        "10030",
        "VILLAREGGIA",
        "TO",
        "Torino",
        ""
    ],
    [
        "IT",
        "10030",
        "VISCHE",
        "TO",
        "Torino",
        ""
    ]
Daniel
  • 36,833
  • 10
  • 119
  • 200
  • Straightforward, the 5th missing parameter just corresponds to the action column. To add an _empty_ field to the data source seems to be a workaround rather then an answer. – Alberto De Caro Nov 05 '12 at 14:28
9

Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:

https://datatables.net/examples/ajax/null_data_source.html

Antônio Medeiros
  • 3,068
  • 1
  • 27
  • 22
6

Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.

$(document).ready(function() {
  var table = $('#userTable').DataTable( {
        "sAjaxSource": "/MyApp/proctoring/user/getAll",
        "sAjaxDataProp": "users",
        "columns": [
                    { "data": "username" },
                    { "data": "name" },
                    { "data": "surname" },
                    { "data": "status" },
                    { "data": "emailAddress" },
                    { "data" : "userId" }
                  ],
        "aoColumnDefs": [
           {
                "aTargets": [5],
                "mData": "userId",
                "mRender": function (data, type, full) {
                    return '<button href="#"' + 'id="'+ data + '">Edit</button>';
                }
            }
         ]
    } );

    $('#userTable tbody').on( 'click', 'button', function () {
        var data = table.row( $(this).parents('tr') ).data();
        console.log(data);
        $('#userEditModal').modal('show');
    });

} );
Bilbo Baggins
  • 2,899
  • 10
  • 52
  • 77
0

Action

 [HttpGet]
        public JsonResult Roles()
        {
            var data = _accountService.GetRoles().Result;
            return Json(data);
        }

CDN

<link rel="stylesheet"
 href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.css" /> 
 <script
 src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.js"></script>

Html

<table class="table table-hover" id="table">
                  <thead>
                      <tr>
                          <th>Code</th>
                          <th>Name</th>
                          <th></th>
                      </tr>
                  </thead>
              </table>

DataTable Code

<script>
        $(document).ready(function(){
            debugger;
            $("#table").dataTable({
                "ajax": {
                    "url": "/Admistration/Roles",
                    "type": "GET",
                    "dataSrc": "",
                     "datatype": "json"
                },
               "columns": [
                    { "data": "code", "autoWidth": true },
                    { "data": 'name', "autoWidth":true},
                    { "render": function (data, type, full) { return "<a  class='btn btn-danger' onclick=DeleteCustomer('" + full.code + "') ><i class='bi bi-trash3-fill'></i></a>   <a href='#' class='btn btn-primary' onclick=DeleteCustomer('" + full.code + "'); ><i class='bi bi-pencil-square'></i></a>" } }
                ]
            });
        })
   
    </script>
Ragab Mohamad
  • 371
  • 2
  • 4