Ad

Sort Column In Datatable Using Custom Html Attribute With ASP.NET Core

- 1 answer

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 ?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad