3

I have a model called Server with the attributes ComputerName and Type. All of the servers are listed on a table like this: enter image description here

I want this table to be updated in Real-Time everytime a new server is added. For doing that I'm using Signal R. However when a new server is added, the previous servers are duplicated and added once more: enter image description here

I'm not sure why this is happening. Here is my code where the table is created:

 <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.ComputerName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Type)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Estado)
                </th>

            </tr>
        </thead>
        <tbody id="table">
        </tbody>
    </table>

And the javascript code:

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="~/lib/microsoft/signalr/dist/browser/signalr.js"></script>
<script>
   
        var connection = new signalR.HubConnectionBuilder().withUrl("/myHub").build();

        connection.on("UpdateServers", function () {
            $.get("/api/ServersAPI", function (data) {
                console.log(data);
                $.each(data, function (i, item) {
                    var img;

                    if (item.state == "Ready") {
                         img = "<img src='~/icons/enabled.png' style='width: 20px; height: 20px'/>"
                    } else
                    {
                        if (item.state == "Reboot Pending") {
                             img = "<img src='~/icons/warning.png' style='width: 20px; height: 20px'/>"
                        }

                    } 
                    
                    $('#table').append("<tr><td>" + item.computerName + "</td><td>" + item.type + "</td><td>" + img + "</td>");



                });

            });
        });

  

        connection.start().then(() => {
            connection.invoke("PostServers").catch(function (err) {
                return console.error(err.toString());
            });

        });



</script>

What is wrong with the code for it to be adding the same information multiple times? I'm avaliable to answer any questions or share more code. Thank you in advance.

Sam
  • 247
  • 5
  • 16
  • You can try to add data manually and then update it in real time without Signal R to test if there is a problem. If it is caused by the problem, you can refer to this post:https://stackoverflow.com/questions/64062303/how-to-handle-updates-in-the-right-way-using-signalr – Tupac Oct 15 '21 at 06:01

0 Answers0