0

I have a table with three columns: Id, Name and Size

In MVC view I have like:

<table class="table table-hover">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Size</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.Items)
        {
            <tr>
                <td>
                    @item.Id
                </td>
                <td>
                    @item.Name
                </td>
                <td>
                    <span data-sort="@item.SizeVal">
                        @item.Size
                    </span>
                </td>
            </tr>
        }
    </tbody>
</table>

The Size looks like: 15 MB or 1.25 GB etc.

And SizeVal from data-sort attribute is a number converted from MB, GB to Bytes.

In javascript, I initialise datatable object

var $fileTable = $(".table");

var dtable = $fileTable.DataTable({
    "columnDefs": [
        { "type": "any-number", targets: 2 }
    ],
    order: [[2, "desc"]],
    //responsive: true,
    stateSave: true,
    pageLength: 25
});

I want when sort Size column, should take in consideration value from data-sort attribute.

I tried with

"columnDefs": [
   { "type": "any-number", targets: 2 }
],

but not sort well.

How to achieve this ?

Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
  • [Link1](https://stackoverflow.com/questions/20286162/custom-sorting-on-values-in-a-data-sort-attribute-with-jquery-datatables) [Link2](https://datatables.net/examples/advanced_init/html5-data-attributes.html) – Dani Jan 03 '19 at 08:09

1 Answers1

0

Datatables read the data-sort that is in the current td.

So rather than putting it in the span you need to put it in the td as shown in the HTML part here here

<td data-sort="@item.SizeVal">
    @item.Size
</td>

Please also read the documentation explaining it.

Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57