Back

Technologies:

javascriptjavascript
avatar
Tolerim
24 days ago

How can I display a data list in a table on the front end of a CRUD Asp.Net Core MVC application using JavaScript code?

After successfully running the CRUD project tutorial using ASP.NET Core MVC, I decided to incorporate a list of phone numbers for each employee in the project. I achieved this by adding Telefono object variables to the Empleado structure, which is stored in a different SQL Server table and linked to the Empleado table using the idEmpleado foreign key. Each Empleado object can now be linked to multiple Telefono objects. The backend aspects of the project are perfect, but I am encountering issues with the JavaScript code. The following function is meant to read the HttpGet request that facilitates the Employee list from the DB, and add the phone numbers of each Empleado's Telefono variable list to a dropdown list in the cells of the Employee list. However, this function always returns an empty array of objects. I read that response.json() can only be called once, but I call it from another function in my function. Could someone please assist me with this issue?

If anything in my question is unclear, please let me know, and I will do my best to provide clarification. Also, if there are any issues with my question, please refrain from marking it as bad or wrong. I am a desktop apps and videogame developer, learning web development, and asking for help the best way I know-how.

Here is the code for the function that loads the Employee list and builds the list in the frontend:

// loads Employee list and builds the list in the front end
function MostrarEmpleados() {
    var telefonos = [];
    var className, i = 0;

    fetch("/Home/listaEmpleados")
        .then(response => {
            return response.ok ? response.json() : Promise.reject(response)
        })
        .then(responseJson => {
            if (responseJson.length > 0) {
                $("#tablaEmpleados tbody").html("");

                i = 0;
                responseJson.forEach((empleado) => {

                    className = "telefonos" + i;
                    $("#tablaEmpleados tbody").append(
                        $("<tr>").append(
                            $("<td>").text(empleado.nombreCompleto),
                            $("<td>").addClass(className),
                            $("<td>").text(empleado.refDepartamento.nombre),
                            $("<td>").text(empleado.sueldo),
                            $("<td>").text(empleado.fechaContrato),
                            $("<td>").append(
                                $("<button>").addClass("btn btn-primary btn-sm boton-editar-empleado").text("Editar").data("dataEmpleado",empleado),
                                $("<button>").addClass("btn btn-danger btn-sm ms-2 boton-eliminar-empleado").text("Eliminar").data("dataEmpleado",empleado),
                            )
                        )
                    )
                    telefonos = ObtenerTelefonos(empleado.idEmpleado); // always returns empty array
                    $("." + className).append(
                        $("<select>").addClass("listaTels")
                    );
                    telefonos.forEach((telefono) => {
                        $(".listaTels").append(
                            $("<option>").text(telefono.descripcion + ": " + telefono.numero)
                        )
                    })
                    i++;
                })
            }
        })
}
Additionally, here is the function that is meant to get the Telefono variable list of a specific Empleado, but this function also always returns an empty array:

function ObtenerTelefonos(id) {
    var telefonos = [];
    fetch(`/Telefono/listaTelefonos?idEmpleado=${id}`)
        .then(response => {
            return response.ok ? response.json() : Promise.reject(response)
        })
        .then(responseJson => {
            if (responseJson.length > 0) {

                responseJson.forEach((telefono) => {
                    telefonos.push({
                        idTelefono: telefono.idTelefono,
                        descripcion: telefono.descripcion,
                        numero: telefono.numero,
                        idEmpleado: telefono.idEmpleado
                    });
                })
            }
        })
    return telefonos;
}
Answers(2)
avatar
Vogi
23 days ago
Verified Answer
Hello! It seems like you are encountering an issue with the JavaScript code. Based on the code you provided, it looks like the function ObtenerTelefonos(id) is always returning an empty array. This could be due to the fact that the function is returning before the fetch call is completed. You can try using async/await to ensure that the function waits for the fetch call to complete before returning. Here's an example of how you can modify your code:
var telefonos = [];
    await fetch(`/Telefono/listaTelefonos?idEmpleado=${id}`)
        .then(response => {
            return response.ok ? response.json() : Promise.reject(response)
        })
        .then(responseJson => {
            if (responseJson.length > 0) {

                responseJson.forEach((telefono) => {
                    telefonos.push({
                        idTelefono: telefono.idTelefono,
                        descripcion: telefono.descripcion,
                        numero: telefono.numero,
                        idEmpleado: telefono.idEmpleado
                    });
                })
            }
        })
    return telefonos;
}
You can also try using console.log() to debug your code and see what values are being returned by the fetch call. I hope this helps! Let me know if you have any other questions or if there's anything else I can help you with.

Sources

React + Fetch - HTTP GET Request Examples | Jason Watmore's BlogHow to check if an array is empty using Javascript? - Flexiplejavascript - For loop with fetch returning empty array - Stack OverflowHow to Check if a JavaScript Array is Empty or Not with .lengthjavascript - fetch gives an empty response body - Stack Overflowfetch url in javascript returns empty array - Stack Overflow
avatar
Tolerim
24 days ago
The issue with the ObtenerTelefonos function is that it returns an empty telefonos array outside of the .then() method of the fetch request. Fetch is asynchronous, so return telefonos is executed before the asynchronous fetch function can populate the array. To fix the issue, you can return the fetch promise and chain another .then() method to populate the telefonos array inside it. Here's an updated version of the ObtenerTelefonos function:
return fetch(`/Telefono/listaTelefonos?idEmpleado=${id}`)
        .then(response => {
            return response.ok ? response.json() : Promise.reject(response)
        })
        .then(responseJson => {
            const telefonos = [];

            if (responseJson.length > 0) {
                responseJson.forEach((telefono) => {
                    telefonos.push({
                        idTelefono: telefono.idTelefono,
                        descripcion: telefono.descripcion,
                        numero: telefono.numero,
                        idEmpleado: telefono.idEmpleado
                    });
                });
            }

            return telefonos;
        });
}
In the MostrarEmpleados function, you can call ObtenerTelefonos inside the first .then() method of the fetch(/Home/listaEmpleados) request. Here's an example:
fetch("/Home/listaEmpleados")
        .then(response => {
            return response.ok ? response.json() : Promise.reject(response)
        })
        .then(responseJson => {
            if (responseJson.length > 0) {
                $("#tablaEmpleados tbody").html("");

                let i = 0;
                responseJson.forEach((empleado) => {

                    const className = "telefonos" + i;
                    $("#tablaEmpleados tbody").append(
                        $("<tr>").append(
                            $("<td>").text(empleado.nombreCompleto),
                            $("<td>").addClass(className),
                            $("<td>").text(empleado.refDepartamento.nombre),
                            $("<td>").text(empleado.sueldo),
                            $("<td>").text(empleado.fechaContrato),
                            $("<td>").append(
                                $("<button>").addClass("btn btn-primary btn-sm boton-editar-empleado").text("Editar").data("dataEmpleado",empleado),
                                $("<button>").addClass("btn btn-danger btn-sm ms-2 boton-eliminar-empleado").text("Eliminar").data("dataEmpleado",empleado),
                            )
                        )
                    );

                    ObtenerTelefonos(empleado.idEmpleado)
                        .then((telefonos) => {
                            $("." + className).append(
                                $("<select>").addClass("listaTels")
                            );

                            telefonos.forEach((telefono) => {
                                $(".listaTels").append(
                                    $("<option>").text(telefono.descripcion + ": " + telefono.numero)
                                );
                            });
                        });

                    i++;
                });
            }
        });
}
In this version of MostrarEmpleados, ObtenerTelefonos is called inside the forEach loop, and its result is passed as an argument to another .then() method that populates the dropdown list with phone numbers.
;