1

I'm pulling raw JSON in to fill out my DataTable.

The problem is that things like pagination and sorting don't work.

I'm not pulling info from a Database, I'm actually pulling data from AWS.

From AWS --> Cache File --> JSON --> DataTables.

My JSON looks like so:

{
"count": 332,
"data": [
  {
  "account": "NetOps",
  "architecture": "x86_64",
  "block_devices": [
    {
      "delete_on_terminate": true,
      "name": "/dev/sda1",
      "status": "attached",
      "volume_id": "vol-secret"
    }
  ],
  "ebs_optimized": false,
  "group_name": null,
  "hypervisor": "xen",
  "id": "i-secret",
  "instance_type": "m1.small"}
]} 

Of course the real result returns 323 records...

The JSON is valid JSON according to JSON Lint

Here is what I use for DataTables:

<script>
  $(document).ready(function() {
  $('#ec2_table').DataTable({
            "serverSide": true,
            "ajax": '/ec2',
            "columns": [
        { "data": "id" },
        { "data": "name" },
        { "data": "architecture" },
        { "data": "instance_type" },
        { "data": "image_id" },
        { "data": "platform" },
        { "data": "state" },
        { "data": "account" },
                    ],
         "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            dom: 'T<"clear">lfrtip',
            tableTools: {
        "sSwfPath":    "/static/js/DataTables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
    }
    });
});

</script>

Pagination, Column Sorting, Searching are all inoperative.

And my Jinja/HTML looks like so:

<table id="ec2_table" class="order-column display compact" cellspacing="0"    width="98%">
  <thead>
    <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Architecture</th>
          <th>InstType</th>
          <th>Image ID</th>
          <th>Platform</th>
          <th>State</th>
          <th>Account</th>
    </tr>
  </thead>
</table>
5
  • can you post the html for ec2_table? Commented Apr 9, 2015 at 20:48
  • Your javascript code seems to be missing a closing } and a closing ) for .ready(function() { Commented Apr 9, 2015 at 20:55
  • Hate to be a bother but does the search bar etc. show up? And are you getting any sort of javascript error? Commented Apr 9, 2015 at 21:26
  • Search Bar does show. Dev Tools in Chrome shows no errors. Commented Apr 9, 2015 at 21:40
  • I updated my answer. I hope it helps. Commented Apr 21, 2015 at 21:35

1 Answer 1

2

I have been looking at the dataTables documentation and I think the problem is with your JSON.

server-side manual

this is the example they gave. count: isn't one of the listed parameters the datatable is expected. Let me know if changing the JSON to return "draw". "recordsTotal", "recordsFiltered", and "data" as the parameters works. As I am still learning DataTables myself.

{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
    [
        "Angelica",
        "Ramos",
        "System Architect",
        "London",
        "9th Oct 09",
        "$2,875"
    ],
    [
        "Ashton",
        "Cox",
        "Technical Author",
        "San Francisco",
        "12th Jan 09",
        "$4,800"
    ],
    ...
]

}

I finally got all of this to work!

You will need this class to play api for the ajax/json

Imports System.Web.Script.Serialization

Public Class DataTableJsonModel
    Public Property draw As Integer
    Public Property start As Integer
    Public Property length As Integer
    Public Property search As SearchModel
    Public Property order As OrderModel()
    Public Property columns As ColumnModel()

    Class ColumnModel
        Public Property Data As String
        Public Property Name As String
        Public Property searchable As Boolean
        Public Property Orderable As Boolean
        Public Property Search As SearchModel
    End Class

    Class SearchModel
        Public Property value As String
        Public Property regex As Boolean
    End Class

    Class OrderModel
        Public Const asc As String = "asc"
        Public Const desc As String = "desc"

        Public Property column As Integer
        Public Property dir As String
    End Class
End Class

Public Class DataTableReturnModel
    Public Property draw As Integer
    Public Property data As Object
    Public Property recordsTotal As Integer
    Public Property recordsFiltered As Integer
    Public Property errorMessage As String
End Class

Public Class AWS
    Public Property instance_type As String
    Public Property id As String
    Public Property architecture As String
    Public Property account As String
    Public Property name As String

    Public Property block_devices As BlockDeviceModel()
    Public Property ebs_optimized As Boolean
    Public Property group_name As String
    Public Property hypervisor As String


    Class BlockDeviceModel
        Public Property delete_on_terminate As Boolean
        Public Property name As String
        Public Property status As String
        Public Property volume_id As String
    End Class
End Class

My Html/javascript will looks like this.

@Code
    ViewData("Title") = "AWSDataTables"
End Code


<script>
    $(document).ready(function () {
        var table = $('#ec2_table').DataTable({
            "serverSide": true,
            "ajax": { url: '/Home/ec2',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                data: function (d) {
                    return JSON.stringify(d);
                },
            },
            "columns": [
        { "data": "id" },
        { "data": "name" },
        { "data": "architecture" },
        { "data": "instance_type" },

            ],
            "lengthMenu": [[10, 25, 50, 100, 1000], [10, 25, 50, 100, 1000]],
            dom: 'T<"clear">lfrtip',
            tableTools: {
                "sSwfPath": "/Scripts/media/js/DataTables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
            }
        });
    });

</script>

<h2>AWSDataTables</h2>

<table id="ec2_table" class="order-column display compact" cellspacing="0" width="98%">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Architecture</th>
            <th>InstType</th>
        </tr>
    </thead>
</table>

And my server-side controller code was this.

Function AWSDataTables() As ActionResult
    Return View()
End Function

<HttpPost()> _
Function ec2(d As DataTableJsonModel) As JsonResult
    Dim dataresults As IEnumerable(Of AWS) = GetAWSTestList()
    Dim filteredData As IEnumerable(Of AWS) = dataresults
    Dim output As New DataTableReturnModel()

    'sorting happens here
    If Not String.IsNullOrEmpty(d.Search.value) Then
        Dim s As String = d.search.value.ToLower
        'this will obviously change based on your class.
        filteredData = dataresults.Where(Function(x) x.id.ToLower.Contains(s) OrElse
                                             x.architecture.ToLower.Contains(s) OrElse
                                             x.name.ToLower.Contains(s))
    End If

    'Ordering happens here
    If Not IsNothing(d.order) AndAlso d.order.Length > 0 Then
        Dim orderM As DataTableJsonModel.OrderModel = d.order(0)
        If Not IsNothing(orderM) Then
            Dim sortDirection As String = orderM.dir
            Dim columnM As DataTableJsonModel.ColumnModel = d.columns.ElementAtOrDefault(orderM.column)
            If Not IsNothing(columnM) AndAlso Not String.IsNullOrEmpty(columnM.Data) AndAlso Not IsNothing(GetType(AWS).GetProperty(columnM.Data)) Then
                If sortDirection = DataTableJsonModel.OrderModel.asc Then
                    filteredData = filteredData.OrderBy(Function(x) GetType(AWS).GetProperty(columnM.Data).GetMethod.Invoke(x, {}))
                Else
                    filteredData = filteredData.OrderByDescending(Function(x) GetType(AWS).GetProperty(columnM.Data).GetMethod.Invoke(x, {}))
                End If
            End If
        End If
    End If

    output.data = filteredData.Skip(d.start).Take(d.length)
    output.recordsFiltered = filteredData.Count
    output.recordsTotal = dataresults.Count

    Return Json(output)
End Function
Sign up to request clarification or add additional context in comments.

1 Comment

I have been working on this and it turns out. If you do serverside you have to implement the search, sorting and paging all on your own. I will update this answer once I have gotten every aspect done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.