Skip to main content

Ajax from DataTable is not working in .net 6

I dont get any errors in the console. And the breakpoint in the method of the controller is never called. (sorry for my bad english). The problem is that the method is never called from the ajax. Please help.

Html:

<!-- Modal -->
<div id="modal-inclusion" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title text-center" id="exampleModalCenterTitle">Solicitar inclusión</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Header -->
                <div class="card-header">
                    <div class="row justify-content-between align-items-center flex-grow-1">
                        <div class="col-12 col-md">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="card-header-title">Users</h5>
                            </div>
                        </div>

                        <div class="col-auto">
                            <!-- Filter -->
                            <form>
                                <!-- Search -->
                                <div class="input-group input-group-merge input-group-flush">
                                    <div class="input-group-prepend input-group-text">
                                        <i class="bi-search"></i>
                                    </div>
                                    <input id="datatableWithSearchInput" type="search" class="form-control" placeholder="Search users" aria-label="Search users">
                                </div>
                                <!-- End Search -->
                            </form>
                            <!-- End Filter -->
                        </div>
                    </div>
                </div>
                    <!-- Table -->
                    <div class="table-responsive datatable-custom">
                        <table id="tb_renovaciones_inclusion js-datatable table table-borderless table-thead-bordered table-nowrap table-align-middle card-table"
                               data-hs-datatables-options='{
               "order": [],
               "search": "#datatableWithSearchInput",
               "isResponsive": false,
               "isShowPaging": false,
               "pagination": "datatableWithSearchPagination"
             }'>
                            <thead class="thead-light">
                                <tr>
                                    <th scope="col">Poliza</th>
                                    <th scope="col">Tipo</th>
                                    <th scope="col">Vigencia</th>
                                    <th scope="col">Inclusión</th>
                                </tr>
                            </thead>

                            <tbody>
                            </tbody>
                        </table>
                    </div>
                    <!-- End Table -->
                    <!-- Footer -->
                    <div class="card-footer">
                        <!-- Pagination -->
                        <div class="d-flex justify-content-center justify-content-sm-end">
                            <nav id="datatableWithSearchPagination" aria-label="Activity pagination"></nav>
                        </div>
                        <!-- End Pagination -->
                    </div>
                    <!-- End Footer -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>
<!-- End Modal -->

Javascript:

<script>
    (function(){
        console.log("Se hace la llamada al controlador")
        $('#tb_renovaciones_inclusion').DataTable({

            "destroy": true, //Para destruir la inicializacion del init
            "order": [[3, "asc"]], // asc y desc - ya no xq no lo estoy ordenando en el store procedure sql
            "paging": false, // Para que te muestre todo los valores
            "isResponsive": false, // Falta averiguar que realiza
            "isShowPaging": false, // Falta averiguar que realiza

            "sScrollY": "100%", // Tiene que ver con el scroll de la tabla
            "sScrollX": false, // Tiene que ver con el scroll de la tabla

            "ajax": {
                "url": "@Url.Action("ListarRenovacionesTotales", "JsonConexion")",
                "type": "GET",
                "datatype": "json"
            },
            "columns": [
                {
                    "render": function (data, type, full, meta) {
                        console.log(full);
                        return '<td><span class="d-block text-primary text-center">' + full.numeroPoliza + '</span><span class="badge bg-soft-info text-info d-flex text-center justify-content-center align-items-center">' + full.descripcionCortoRamo + '</span></td>';
                    }
                },
                {
                    "render": function (data, type, full, meta) {
                        return '<td><span class="d-block mb-0 h5">' +full.tipoVigencia+ '</span><span class="d-block fs-5">' +full.formaPagoPrima+ '</span></td>';
                    }
                },

                {
                    "render": function (data, type,full, row) {
                        return '<td><span class="d-block mb-0"> I: ' + full.vigenciaInicio+ '</span><span class="d-block fs-5"> F: ' + full.vigenciaFin+ '</span></td>';
                    }
                },

                {
                    "render": function (data, type, full, meta) {
                        return '<td><a class="justify-content-center d-flex align-items-center" href="/Cliente/renovar-poliza-riesgos-humanos?id=' + full.id_Poliza+'"><i class="fs-2 fa-solid fa-repeat" style = "color: #0700C9;" ></i></a></td>';
                    }
                },
                // { "data": "msjEnviados" },
            ]

        });
        console.log("el método ya se ejecutó")

    })()
   

</script>

Controller:

[HttpGet]
public JsonResult ListarRenovacionesTotales()
{
    string userName = _httpContextAccessor.HttpContext?.User?.Identity?.Name; //ID USUARIO

    DetalleUsuarioDA detalleUsuarioDA = new DetalleUsuarioDA();

    DetalleUsuario detalleUsuario = detalleUsuarioDA.GetDetalleUsuario(userName);

    List<QueryPolizaPrimaViewModel> lista = new List<QueryPolizaPrimaViewModel>();

    var polizaDA = new PolizaDA();

    lista = polizaDA.ListarPolizaPrimaClienteSctr(detalleUsuario.Fk_Cliente).ToList();

    if (lista.Count > 0)
    {
        return Json(new
        {
            data = lista.Select(item => new {
                Id_Poliza = item.Id_Poliza,
                Fk_Cliente = item.Fk_Cliente,
                NumeroPoliza = item.NumeroPoliza,
                Fk_Ramo = item.Fk_Ramo,
                VigenciaInicio = item.VigenciaInicio.ToString("dd/MM/yyyy"),
                VigenciaFin = item.VigenciaFin.ToString("dd/MM/yyyy"),
                DocumentoPrima = item.DocumentoPrima,
                FormaPagoPrima = item.FormaPagoPrima,
                PrimaNeta = item.PrimaNeta,
                ImporteComisionBroker = item.ImporteComisionBroker,
                Moneda = item.Moneda,
                EstadoPoliza = item.EstadoPoliza,
                Asegurado = item.Asegurado,
                TipoVigencia = item.TipoVigencia,
                DescripcionCortoRamo = item.DescripcionCortoRamo,
            })
        });
    }
    else
    {
        // Si la lista está vacía, retorna un mensaje de error
        return Json(new { data = "lista-vacia" });
    }


}

I tried put breakpoints and use console.log(full) but that does not working.

Via Active questions tagged javascript - Stack Overflow https://ift.tt/bKe6CYR

Comments

Popular posts from this blog

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...