DataTables and Visual Studio integration.

DataTables and Visual Studio integration.

JZanabriaJZanabria Posts: 11Questions: 1Answers: 0
edited December 2023 in Free community support

Hi, I'm having a problem using DataTables into Visual Studio 2019.
I can´t have the "select" option into the table.
Mi ASP.NET program is:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="PruebaGrillas.aspx.vb" Inherits="ECOMMERCEAPI.PruebaGrillas"  %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.2.7/css/select.dataTables.min.css" />

<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/select/1.2.7/js/dataTables.select.min.js"></script>


    <script type="text/javascript">
        $(document).ready(function () {
           

            $('#miTabla').DataTable({
                pageLength: 5,
                lengthMenu: [5, 10, 25, 50],
                searching: true,
                paging: true,
                ordering: true,
                info: true,
                autoWidth: false,
                columnDefs: [
                    { targets: 0, className: 'dt-left' }, // Centro dt-center
                    { targets: 1, className: 'dt-left' },  // Derecha dt-right
                    { targets: 2, className: 'dt-right' },   // Izquierda dt-left
                    { targets: 3, className: 'dt-right' },
                    { targets: 4, className: 'dt-right' },
                    { targets: 5, className: 'dt-right' }
                ],

                language: {
                    search: "Buscar:",
                    lengthMenu: "Mostrar _MENU_ entradas por página",
                    info: "Mostrando _START_ a _END_ de _TOTAL_ entradas",
                    infoEmpty: "Mostrando 0 a 0 de 0 entradas",
                    infoFiltered: "(filtrado de _MAX_ entradas totales)",
                    paginate: {
                        first: "Primero",
                        previous: "Anterior",
                        next: "Siguiente",
                        last: "Último"
                    },
                    select: true
                }
            });

            $('#miTabla').on('select', function (e, dt, type, indexes) {
                // Obtener los datos de la fila seleccionada
                var rowData = dt.rows(indexes).data().toArray();

                // Hacer una solicitud AJAX para enviar los datos al servidor
                $.ajax({
                    type: 'POST',
                    url: 'PruebaGrillas.aspx/ProcesarFilaSeleccionada',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ rowData: rowData }),
                    success: function (response) {
                        // Manejar la respuesta del servidor si es necesario
                        console.log(response.d);
                    },
                    error: function (error) {
                        console.error(error);
                    }
                });
            });
        });
    </script>

    <style>
        .dataTables_info {
    font-size: 10px; /* Ajusta el tamaño según tus necesidades */
}
        .dataTables_paginate {
    font-size: 10px; /* Ajusta el tamaño según tus necesidades */
}
       #miTabla_wrapper .dataTables_length, #miTabla_wrapper .dataTables_filter {
    font-size: 10px !important; /* Ajusta el tamaño según tus necesidades */
}

    </style>

</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>

        <div>

            <div class="container-fluid" id="Div9" runat="server" visible="true" style="width:70%;">

                <div class="panel panel-default">
                    <div class="panel-heading" style="font-size: 14px; padding: 3px 5px; margin-bottom: 0;">
                        <h5 class="small">TITULAR DE LA RESERVA</h5>

                    </div>
                    <div class="panel-body">



                        <asp:Literal ID="MiLiteral" runat="server" />
                    </div>
                </div>
            </div>


        </div>
    </form>
</body>
</html>

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Answers

  • allanallan Posts: 62,990Questions: 1Answers: 10,367 Site admin

    I can´t have the "select" option into the table.

    Why not? It looks like you have it in the above.

    Per the forum rules and the template help text you deleted, please link to a test case showing the issue so I can debug it and offer some help.

    Allan

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0

    Allan, thank you for your answer.
    If you want, I can send you the Web Form and the Image of the result.
    I'd like to have the table with a select option available to capture the content into my program in the server side.
    We are building a complex solution and we'd like to replace the GridView offered by Microsoft with another grid. We've found DataTables and we test it with excellent results, but now I need to have 2 main features.
    1) Select a row or a cell and obtain the content
    2) Edit cells and modify the data base with this change.

    I've seen examples into DataTables.net web pages and THIS is what I need.
    Please, tell me how I can send you the information.

    Thank a lot.
    Jorge

  • kthorngrenkthorngren Posts: 21,083Questions: 26Answers: 4,908
    edited December 2023

    In your code snippet I don't see a table element for Datatabes to initialize. It's looking for a table with the ID of miTabla. See the HTML requirements for details.

    Not a Datatables issue but you probably need to load jquery.js on line 18 before bootstrap.js on line 12.

    Check for errors in your browser's console.

    You can send Allan the info directly by clicking his name above to send a PM.

    Kevin

  • allanallan Posts: 62,990Questions: 1Answers: 10,367 Site admin

    Hi Jorge,

    Great to hear that DataTables sounds like it fits the bill for you.

    It's always quite difficult to get examples of .NET solutions I know. You aren't able to upload it to the web somewhere?

    I'm not clear on what the problem with Select is at the moment. Are you getting an error from it, or is it just doing nothing? What you have looks like it should allow row selection.

    Allan

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0

    Thank you Kevin and Allan.
    The table works well, I can fill it from my "server side" without problem using a SELECT to a MySql data base.
    I can see the selector of number of rows at the left side up, Search at the right up and at the bottom the pagination.
    This work as a normal grid showind data.
    When I put the " select: true " attribute I don´t see any change in the table and I can´t select a row or a cell.
    It doesn´t work.
    I don´t know if I can explain well the problem. There isn´t any change into the grid when I put "select: true".

    Besides, I need to know how I have to modify the Table to be editable (some cells).
    I´ve seen some examples at the web site but they don´t work.

    Jorge

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0

    Kevin, The definition of the Table is at

    <asp:Literal ID="MiLiteral" runat="server" />

    Where the program at server side format a string with the Table definition.

    This is the program at server side:

    Dim contenidoTabla As New StringBuilder()

        contenidoTabla.Append("<table id='miTabla' class='table table-striped table-bordered dt-responsive nowrap' style='width: 60%;font-size: 10px;'>")
        contenidoTabla.Append("<thead><tr>")
        contenidoTabla.Append("<th style='width: 10%'>Reserva</th>")
        contenidoTabla.Append("<th style='width: 10%'>Estado</th>")
        contenidoTabla.Append("<th style='width: 20%'>Total_Reserva</th>")
        contenidoTabla.Append("<th style='width: 20%'>Facturado</th>")
        contenidoTabla.Append("<th style='width: 20%'>Cobrado</th>")
        contenidoTabla.Append("<th style='width: 20%'>Saldo</th>")
        contenidoTabla.Append("</tr></thead>")
        contenidoTabla.Append("<tbody>")
    
        Dim datos As List(Of TuClase) = ObtenerDatos()
    
        For Each fila As TuClase In datos
            contenidoTabla.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td></tr>",
                                        fila.Columna1, fila.Columna2, fila.Columna3, fila.Columna4, fila.Columna5, fila.Columna6)
        Next
    
        contenidoTabla.Append("</tbody></table>")
    
        ' Asignar el HTML generado al control Literal
        MiLiteral.Text = contenidoTabla.ToString()
    

    The Function: ObtenerDatos() is for read the data from MySql. Create a List of Class with the data in each cell.

    This works well.

  • kthorngrenkthorngren Posts: 21,083Questions: 26Answers: 4,908

    Looks like you have select: true inside the language option. Move it outside so its at the same level.

    The best option is to use the Editor for your editing operations. All the code is built, ready to go.

    If you choose to use your own you will need to get the rows, as you show in your code, then send via ajax to the server. What is returned from the server? If its the updated rows the use row().data() as a setter for each row.

    Kevin

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0

    Kevin, I think that select: true is out the languaje option.

    language: {
    search: "Buscar:",
    lengthMenu: "Mostrar MENU entradas por página",
    info: "Mostrando START a END de TOTAL entradas",
    infoEmpty: "Mostrando 0 a 0 de 0 entradas",
    infoFiltered: "(filtrado de MAX entradas totales)",
    paginate: {
    first: "Primero",
    previous: "Anterior",
    next: "Siguiente",
    last: "Último"
    },
    select: true

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0

    Kevin, I've installed Editor. I'll test it.
    Thank you

  • kthorngrenkthorngren Posts: 21,083Questions: 26Answers: 4,908
    edited December 2023

    Its outside of the paginate option of language but still inside language option. Move it between lines 59 and 60.

    Kevin

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0

    Kevin, you were right.
    It works the select option now.
    Thank you!!!!

    Jorge

  • kthorngrenkthorngren Posts: 21,083Questions: 26Answers: 4,908
    edited December 2023

    Good, let us know if you have Editor questions.

    Kevin

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0

    A lot of questions.
    First, I can´t load the Mysql tables.

    ERROR 1452 (23000) at line 196: Cannot add or update a child row: a foreign key constraint fails (datatables.user_dept, CONSTRAINT user_dept_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0
    edited December 2023

    Following with the Table, now I select the row BUT I can't have the result at the server side.

     $('#miTabla').on('select', function (e, dt, type, indexes) {
                    // Obtener los datos de la fila seleccionada
                    var rowData = dt.rows(indexes).data().toArray();
    
                    // Hacer una solicitud AJAX para enviar los datos al servidor
                    $.ajax({
                        type: 'POST',
                        url: 'PruebaGrillas.aspx/ProcesarFilaSeleccionada',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify({ rowData: rowData }),
                        success: function (response) {
                            // Manejar la respuesta del servidor si es necesario
                            console.log(response.d);
                        },
                        error: function (error) {
                            console.error(error);
                        }
                    });
                });
    

    At server side:

    <WebMethod>
        Public Shared Function ProcesarFilaSeleccionada(rowData As Object()) As String
            
    
            Dim reserva As String = rowData(0)("Reserva").ToString()
    
           
            Return "something"
    
        End Function
    

    Edited by Kevin: Syntax highlighting. Details on how to highlight code using markdown can be found in this guide

  • kthorngrenkthorngren Posts: 21,083Questions: 26Answers: 4,908

    Are you using the Editor or your own code. With the Editor you don't need the select event. See this Simple Editor example.

    I can't have the result at the server side

    Use the browser's network inspector to see the XHR request parameters sent to the server. I'm not familiar with .NET to help with how to retrieve the POST data sent.

    Kevin

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0

    OK Thank you Kevin.

    Best Regards,

    Jorge

  • JZanabriaJZanabria Posts: 11Questions: 1Answers: 0

    I've found why didn´t work the selection.
    I've changed in this sentence:

    $('#miTabla').on('select', function (e, dt, type, indexes)

    select by select.dt and it works well.

    $('#miTabla').on('select.dt', function (e, dt, type, indexes)

  • allanallan Posts: 62,990Questions: 1Answers: 10,367 Site admin

    Yes, if you attach the listener with jQuery you need to add thedt name space. If you use on() you don't.

    Allan

Sign In or Register to comment.