Home > Net >  Datatable skips the configuration data of the columns
Datatable skips the configuration data of the columns

Time:05-27

I am working with net core 5, I have a view with a Datatable (jQuery), but it is not taking the configuration of the columns, I already searched in detail, deleted cookies, cache, etc and it is still the same, I cannot find where the problem could be.

This is the View:

@model IEnumerable<WebProcesoTela.Models.VAlmacenEntSalHiloModel>

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

<div id="divContainer" >
    <!-- Encabezados del formulario -->
    <div >
        <div >
            <!-- Titulo del formulario -->
            <div >
                <h3>Seguimiento Entradas y Salidas de Hilo</h3>
            </div>
            <!-- Botones de acciones -->
            <div >
                <div >
                    @*<button href="#WinModal" id= "btnNewOc" type="button" asp-controller="DoctosAlmMaster" asp-action="CreateByOc"  data-bs-toggle="modal" title="Nuevo Elemento OC" ><i ></i> Nuevo</button>*@
                    <!-- Menu de Acciones -->
                    <div >
                        <button type="button"  data-bs-toggle="dropdown" aria-expanded="false">Acciones</button>
                        <ul >
                            <li><a  href="/AlmacenSaldos/Index" id="btnIndex"><i ></i> Inventario de Almacenes</a></li>
                            <li ><strong> Accesos rápidos</strong></li>
                            <li><hr  style="margin-top: -10px;"></li>
                            <li><a  href="/DoctosAlmMaster/Index" id="btnIndex"><i ></i> Movimientos de Almacén</a></li>
                            <li><a  href="/HiloOcMaster/Index" id="btnIndex"><i ></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 >
        <table id="tableGridE-S" >
            <thead >
                <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 >
                <!-- 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>
}

This is the Controller:

// 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 });
}

and finally the Javascript file

/* ********************** */
/* 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 () {});

The problem is that the columns take default width and not the one I have put in the js file. Any help is welcome.

CodePudding user response:

It is very strange, since I have other Datatables configured in the same way and they work without any problem. The solution was:

In the .js file remove the option

autoWidth: false, // Turn off autowidth

Also change the column width definition to pixels instead of percentage:

{ 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] }

With these changes, the columns are now displayed correctly. thanks for your help

  • Related