Datatable跳过列的配置数据

Datatable skips the configuration data of the columns

我正在使用 net core 5,我有一个带有数据表 (jQuery) 的视图,但它没有采用列的配置,我已经详细搜索过,删除了 cookies,缓存,等等,还是一样,我找不到问题出在哪里。

这是视图:

@model IEnumerable<WebProcesoTela.Models.VAlmacenEntSalHiloModel>

@{
    ViewData["Title"] = "Index";
}

<div id="divContainer" class="container-fluid">
    <!-- Encabezados del formulario -->
    <div class="container container-fluid">
        <div class="row">
            <!-- Titulo del formulario -->
            <div class="col-md-8">
                <h3>Seguimiento Entradas y Salidas de Hilo</h3>
            </div>
            <!-- Botones de acciones -->
            <div class="col-md-4 text-end">
                <div class="container mt-1 mb-1">
                    @*<button href="#WinModal" id= "btnNewOc" type="button" asp-controller="DoctosAlmMaster" asp-action="CreateByOc" class="btnNewOc btn btn-primary btn-md" data-bs-toggle="modal" title="Nuevo Elemento OC" ><i class="fa-solid fa-plus"></i> Nuevo</button>*@
                    <!-- Menu de Acciones -->
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Acciones</button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/AlmacenSaldos/Index" id="btnIndex"><i class="fa-solid fa-barcode"></i> Inventario de Almacenes</a></li>
                            <li class="p-3"><strong> Accesos rápidos</strong></li>
                            <li><hr class="dropdown-divider" style="margin-top: -10px;"></li>
                            <li><a class="dropdown-item" href="/DoctosAlmMaster/Index" id="btnIndex"><i class="fa-solid fa-link"></i> Movimientos de Almacén</a></li>
                            <li><a class="dropdown-item" href="/HiloOcMaster/Index" id="btnIndex"><i class="fa-solid fa-link"></i> Órdenes de Compra</a></li>
                        </ul>
                    </div>
                    <!-- Incluir el boton Refrescar -->
                    <partial name="~/Views/Shared/Controls/_BtnReloadDatatable.cshtml"/>
                </div>
            </div>
        </div>
    </div>      <!-- Fin Encabezado Formulario-->

    <hr/>
    <!-- Mostrar los mensajes del controlador -->
    <script type="text/javascript" src="/js/site.js"></script>
    @if (!String.IsNullOrEmpty(@ViewBag.Message)) {
        <partial name="~/Views/Shared/Controls/_MessageBoard.cshtml"/>
        ViewBag.Message = "";
    }

    <div class="table table-responsive">
        <table id="tableGridE-S" class="display cell-border">
            <thead class="tableHead-sm">
                <tr>
                    <th></th>   <!-- Oculto @Html.DisplayNameFor(model => model.DoctoAlmId) -->
                    <th>@Html.DisplayNameFor(model => model.Folio)</th>
                    <th>@Html.DisplayNameFor(model => model.Fecha)</th>
                    <th>@Html.DisplayNameFor(model => model.Observaciones)</th>
                    <th></th>   <!-- Oculto @Html.DisplayNameFor(model => model.ConceptoInvId) -->
                    <th>@Html.DisplayNameFor(model => model.ConceptoInvName)</th>
                    <th>@Html.DisplayNameFor(model => model.TipoMovimiento)</th>
                    <th></th>   <!-- Oculto @Html.DisplayNameFor(model => model.OrdenCompraId) -->
                    <th>@Html.DisplayNameFor(model => model.FolioOC)</th>
                    <th></th>   <!-- Oculto @Html.DisplayNameFor(model => model.HilanderoId) -->
                    <th>@Html.DisplayNameFor(model => model.HilanderoClave)</th>
                    <th></th>   <!-- Oculto @Html.DisplayNameFor(model => model.HiloOCDetId) -->
                    <th></th>   <!-- Oculto @Html.DisplayNameFor(model => model.ArticuloId) -->
                    <th></th>   <!-- Oculto @Html.DisplayNameFor(model => model.HiloId) -->
                    <th>@Html.DisplayNameFor(model => model.HiloName)</th>
                    <th></th>   <!-- Oculto @Html.DisplayNameFor(model => model.TejedorId) -->
                    <th>@Html.DisplayNameFor(model => model.TejedorShort)</th>
                    <th></th>   <!-- Oculti @Html.DisplayNameFor(model => model.AlmacenDestinoId) -->
                    <th></th>   <!-- Oculto @Html.DisplayNameFor(model => model.AlmacenDestinoShort) -->
                    <th>@Html.DisplayNameFor(model => model.FolioDocto)</th>
                    <th>@Html.DisplayNameFor(model => model.Lote)</th>
                    <th>@Html.DisplayNameFor(model => model.UnidadesPedidas)</th>
                    <th>@Html.DisplayNameFor(model => model.ImporteTotalOC)</th>
                    <th>@Html.DisplayNameFor(model => model.Unidades)</th>
                    <th>@Html.DisplayNameFor(model => model.CostoUnitario)</th>
                    <th>@Html.DisplayNameFor(model => model.CostoTotal)</th>
                    <th>@Html.DisplayNameFor(model => model.Cancelado)</th>
                </tr>
            </thead>
            <tbody class="tableBody-sm">
                <!-- Render Datatable -->
            </tbody>
        </table>
    </div>
</div>
@section scripts{
    <!-- Para usar las funciones del grid -->
    <script type="text/javascript" src="/js/dtg_config/AlmacenEntSalHilo.js"></script>
}

这是控制器:

// GET: VAlmacenEntradasHiloController
public IActionResult Index(string sMsgType, string sMessage)
{
    ViewBag.MsgType = sMsgType;
    ViewBag.Message = sMessage;

    List<VAlmacenEntSalHiloModel> lstVAlmacenEntradasHiloModel = Singleton.Instance.EntityManager.GetEntities<VAlmacenEntSalHiloModel>();
    return View(lstVAlmacenEntradasHiloModel);
}


/* ***************************** */
/* Cargar los datos para el Grid */
/* ***************************** */
[HttpPost]
public IActionResult GetDataList()
{
    var draw = Request.Form["draw"].FirstOrDefault();
    var start = Request.Form["start"].FirstOrDefault();
    var length = Request.Form["length"].FirstOrDefault();
    var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
    var sortColumnDir = Request.Form["order[0][dir]"].FirstOrDefault();
    var searchValue = Request.Form["search[value]"].FirstOrDefault().ToUpper();

    pageSize = length != null ? Convert.ToInt32(length) : 0;
    skip = start != null ? Convert.ToInt32(start) : 0;
    recordsTotal = 0;

    List<VAlmacenEntSalHiloModel> lstVAlmacenEntSalHiloModel = Singleton.Instance.EntityManager.GetEntities<VAlmacenEntSalHiloModel>();
    lstVAlmacenEntSalHiloModel = (from d in lstVAlmacenEntSalHiloModel select d).ToList();

    /* Si tenemos una cadena de busqueda */
    if (searchValue != "")
    {
        lstVAlmacenEntSalHiloModel = lstVAlmacenEntSalHiloModel.Where(x => x.Folio.ToString().Contains(searchValue) ||
                                                                      x.FolioOC.ToUpper().ToString().Contains(searchValue) ||
                                                                      x.FolioDocto.ToUpper().ToString().Contains(searchValue) ||
                                                                      x.Lote.ToUpper().ToString().Contains(searchValue)).ToList();
    }

    /* Si Se eligieron todos los registros */
    if (pageSize == -1)
        pageSize = lstVAlmacenEntSalHiloModel.Count;

    recordsTotal = lstVAlmacenEntSalHiloModel.Count;

    /* Reordenar segun lo solicitado en el Grid */
    switch (sortColumn)
    {
        case "folio":
            if (sortColumnDir == "asc")
                lstVAlmacenEntSalHiloModel = lstVAlmacenEntSalHiloModel.OrderBy(x => x.Folio).Skip(skip).Take(pageSize).ToList();
            else
                lstVAlmacenEntSalHiloModel = lstVAlmacenEntSalHiloModel.OrderByDescending(x => x.Folio).Skip(skip).Take(pageSize).ToList();
            break;

        case "folioDocto":
            if (sortColumnDir == "asc")
                lstVAlmacenEntSalHiloModel = lstVAlmacenEntSalHiloModel.OrderBy(x => x.FolioDocto).Skip(skip).Take(pageSize).ToList();
            else
                lstVAlmacenEntSalHiloModel = lstVAlmacenEntSalHiloModel.OrderByDescending(x => x.FolioDocto).Skip(skip).Take(pageSize).ToList();
            break;

        case "lote":
            if (sortColumnDir == "asc")
                lstVAlmacenEntSalHiloModel = lstVAlmacenEntSalHiloModel.OrderBy(x => x.Lote).Skip(skip).Take(pageSize).ToList();
            else
                lstVAlmacenEntSalHiloModel = lstVAlmacenEntSalHiloModel.OrderByDescending(x => x.Lote).Skip(skip).Take(pageSize).ToList();
            break;

        default:
            break;
    }

    return Json(new { draw, recordsFiltered = recordsTotal, recordsTotal, data = lstVAlmacenEntSalHiloModel });
}

最后 Javascript 文件

/* ********************** */
/* Configuracion del Grid */
/* ********************** */
$(document).ready(function () {
    tableBase = $('#tableGridE-S').DataTable({
        dom: "lBfrtip",                              // Muestra los botones de exportacion (excel, pdf, etc)
        buttons: ["copy", "excel"],                 // Botones de "copy", "excel", "pdf", "csv" y "print"
        filter: true,                               // Filtrado de datos
        info: true,                                 // Resultado de busquedas
        processing: true,                           // Muestra/Oculta la leyenda procesando
        scrollX: true,                              // Scroll Horizontal
        select: true,                               // Permite seleccionar el renglon
        ordering: true,                             // Activa el ordenamiento
        autoWidth: false,                           // Apaga el ancho automatico
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "Todos"]],

        scroller: { "loadingIndicator": true },     // Complemento de representación virtual para DataTables para mostrar muchos datos en la pantalla muy rápidamente.
        serverSide: true,                           // Habilitar procesamiento del lado del servidor
        deferRender: true,                          // Habilitar renderizado diferido para cargar con AJAX                
        responsivePriority: 1,
        data: null,

        ajax: {
            url: "/AlmacenEntSalHilo/GetDataList",
            type: "POST",
            datatype: "json"
        },

        columns: [                                // Definicion de columnas, ID's
            {
                data: "doctoAlmId", name: "doctoAlmId"
            //    render: function (data) {
            //        return "<a href ='#WinModal' data-id='" + data + "' data-bs-toggle='modal' class='btnGrdDetails'>" + ("0000" + data).slice(-4) + "</a>";
            //    }
            },
            {
                data: "folio", name: "folio",
                render: function (value, type, full) {
                    let ordenId = full.doctoAlmId;

                    if (ordenId != null)
                        return "<a href ='#WinModal' data-id='" + ordenId + "' data-bs-toggle='modal' class='btnGrdDetails'>" + full.folio + "</a>";
                    else
                        return " ------ ";
                }
            },
            {
                data: "fecha", name: "fecha",
                render: function (value) {
                    var dt = "";
                    if (value != null)
                        dt = new Date(value).toLocaleDateString('es-MX', { year: 'numeric', month: '2-digit', day: '2-digit' });
                    return dt;
                }
            },
            { data: "observaciones", name: "observaciones" },
            { data: "conceptoInvId", name: "conceptoInvId" },
            { data: "conceptoInvName", name: "conceptoInvName" },
            { data: "tipoMovimiento", name: "tipoMovimiento" },
            { data: "ordenCompraId", name: "ordenCompraId" },
            {
                data: "folioOC", name: "folioOC",
                render: function (value, type, full) {
                    let ordenId = full.ordenCompraId;

                    if (ordenId != null)
                        return "<a href ='#WinModal' data-id='" + ordenId + "' data-bs-toggle='modal' class='btnGrdDetailsOC'>" + full.folioOC + "</a>";
                    else
                        return " ------ ";
                }
            },
            { data: "hilanderoId", name: "hilanderoId" },
            { data: "hilanderoClave", name: "hilanderoClave" },
            { data: "hiloOCDetId", name: "hiloOCDetId" },
            { data: "articuloId", name: "articuloId" },
            { data: "hiloId", name: "hiloId" },
            {
                data: "hiloName", name: "hiloName",
                render: function (data, type, full) {
                    return "<a href ='#WinModal' data-id='" + full.hiloId + "' data-bs-toggle='modal' class='btnGrdDetailsHilo'>" + full.hiloName + "</a>";
                }
            },
            { data: "tejedorId", name: "tejedorId" },
            { data: "tejedorShort", name: "tejedorShort" },
            { data: "almacenDestinoId", name: "almacenDestinoId" },
            { data: "almacenDestinoShort", name: "almacenDestinoShort" },
            { data: "folioDocto", name: "folioDocto" },
            { data: "lote", name: "lote" },
            {
                data: "unidadesPedidas", name: "unidadesPedidas",
                render: $.fn.dataTable.render.number(',', '.', 2, '')
            },
            {
                data: "importeTotalOC", name: "importeTotalOC",
                render: $.fn.dataTable.render.number(',', '.', 2, '$ ')
            },
            {
                data: "unidades", name: "unidades",
                render: $.fn.dataTable.render.number(',', '.', 2, '')
            },
            {
                data: "costoUnitario", name: "costoUnitario",
                render: $.fn.dataTable.render.number(',', '.', 2, '$ ')
            },
            {
                data: "costoTotal", name: "costoTotal",
                render: $.fn.dataTable.render.number(',', '.', 2, '$ ')
            },
            {
                data: "cancelado", name: "cancelado",
                render: function (data, type, row) {
                    if (data == true) { return '<input type="checkbox" checked disabled>'; }
                    else { return '<input type="checkbox" disabled>'; }
                    return data;
                }
            },
        ],

        order: [[1, 'asc']],

        // 0: doctoAlmId[O][F][S], 1: folio, 2: fecha, 3: observaciones[F][S], 4: conceptoInvId[O][F][S], 5: conceptoInvName[F], 6: tipoMovimiento[F],
        // 7: ordenCompraId[O][F][S], 8: folioOC, 9: hilanderoId[O][F][S], 10: hilanderoClave, 11: hiloOCDetId[O][F][S], 12: articuloId[O][F][S],
        // 13: hiloId[O][F][S], 14: hiloName[F], 15: tejedorId[O][F][S], 16: tejedorShort[F], 17: almacenDestinoId[O][F][S], 18: almacenDestinoShort[O][F][S],
        // 19: folioDocto, 20: lote, 21: unidadesPedidas[F][S], 22: importeTotalOC[F][S], 23: unidades[F][S], 24: costoUnitario[F][S],
        // 25: costoTotal[F][S], 26: cancelado[F][S]

        columnDefs: [
            { visible: false, targets: [0, 4, 7, 9, 11, 12, 13, 15, 17, 18] },
            { searchable: false, targets: [0, 3, 4, 5, 6, 7, 9, 11, 12, 13, 14, 15, 16, 17, 18, 21, 22, 23, 24, 25, 26] },
            { sortable: false, targets: [0, 3, 4, 7, 9, 11, 12, 13, 15, 17, 18, 21, 22, 23, 24, 25, 26] },
            { className: "dt-body-center", targets: [1, 2, 4, 6, 8, 26] },
            { className: "dt-body-right", targets: [21, 22, 23, 24, 25] },
            { width: "2%", "targets": [1, 8, 26] },
            { width: "3%", "targets": [19] },
            { width: "4%", "targets": [2, 6] },
            { width: "5%", "targets": [20, 21, 22, 23, 24, 25] },
            { width: "6%", "targets": [5] },
            { width: "8%", "targets": [10, 16] },
            { width: "12%", "targets": [3] },
            { width: "20%", "targets": [14] },
        ],

        // Cargar el Idioma Español //
        language: {
            url: "/js/language_pack/es-MX.json"
        },
    });

    /* ******************** */
    /* Dibujar la DataTable */
    /* ******************** */
    tableBase.draw();

});     // Fin $(document).ready(function () {});

问题是列采用默认宽度,而不是我放入 js 文件中的宽度。 欢迎任何帮助。

这很奇怪,因为我以相同的方式配置了其他数据表并且它们工作没有任何问题。 解决方案是:

在 .js 文件中删除选项

autoWidth: false, // Turn off autowidth

还将列宽定义更改为像素而不是百分比:

{ width: "30px", targets: [1, 6, 19, 26] },
{ width: "40px", targets: [8] },
{ width: "50px", targets: [2] },
{ width: "65px", targets: [21, 22, 23, 24, 25] },
{ width: "100px", targets: [20] },
{ width: "120px", targets: [5, 10, 16] },
{ width: "150px", targets: [3] },
{ width: "250px", targets: [14] }

经过这些更改,列现在可以正确显示了。 感谢您的帮助