通过 jquery 数据 table 中的主键进行数据排序

data sorting via primary key in jquery data table

我已经使用数据 table 在视图页面中显示了数据。我想按照

降序显示数据
public ActionResult Index()
        {
            return View(db.BusinessRegModel.OrderByDescending(v => v.BusinessId).ToList());

        }

BusinessId 是主键。

但是在视图页面中,数据不是通过主键排序的。我正在使用 jquery 数据 table 来显示数据。

<table id="tblBusinessData" class="table" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>Edit/Print</th>
            <th>
                @Html.DisplayNameFor(model => model.RegNum)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.RegDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.NameOfFirm)
            </th>
            //code blocks
             </tr>
    </thead>
     <tbody>
        @foreach (var item in Model)
        {
        <tr>
            <td width="20%">
                @Html.ActionLink("Edit", "Edit", new { id = item.BusinessId }, new { @class = "btn btn-warning" })
                @Html.ActionLink("Print", "Details", new { id = item.BusinessId }, new { @class = "btn btn-danger" })
            </td>
            //code blocks
        

但数据未通过 BusinessId 键按降序排序。我怎样才能做到这一点?我需要按 BusinessId 降序显示数据。

jquery代码

<script type="text/javascript">
            $('#tblBusinessData').DataTable();
    </script>

将列 ID 添加到 HTML 并通过配置将其隐藏:

$('#tblBusinessData').DataTable({
  "columnDefs": [{
    "targets": [0],
    "visible": false
  }],
  "order": [
    [0, "desc"]
  ]
});

如果您能够在将数据发送到 DataTables 之前在数据中设置所需的顺序,则只需设置 order: [] 即可禁用初始排序,同时仍然可以单击列 headers.

$('#tblBusinessData').DataTable({
    order: []
});