Search code examples
asp.net.netasp.net-mvcsignalr-hubsignalr.client

Parsing Database Record in SingalR Javascript Client


I am learning about the ASP.NET Core SignalR. I wrote a basic program under MVC framework that interacts with a SQLite database. This program allows user to perform CRUD operations on the database. I introduced SignalR hub in the program. The server periodically gets list of records from the database, and pushes to the client using hub SendAsync function. In a Javascript hub client, I am trying to parse (and display) the received messages. Everything works (getting list of items from the database, sending through hub) except when accessing an element of an item I get undefined message, although there are three items retrieved from the database with valid values assigned to each element.

Schema for the database (under 'Models' folder):

public class IenState
{
    public int Id { get; set; }   

    public ulong NetId { get; set; }
    public ushort NodeId { get; set; } 
}

Sending messages from sever-end of the hub:

var ienStates = from m in dbcontext.IenState select m;                           
var listdb = await ienStates.ToListAsync();  //here 3-items recovered
await hubContext.Clients.All.SendAsync("IenStateDb", listdb);

Javascript hub client (named IenStateHub.js):

const connection = new signalR.HubConnectionBuilder()
.withUrl("/ienStateHub")
.configureLogging(signalR.LogLevel.Information)
.build();

connection.start().then(function () {        
    document.getElementById("p_nets").innerHTML = "IenStateHub is   'CONNECTED'";               
});

connection.on("IenStateDb", function(message){      
  var dbitem; 
  for (dbitem in message) 
  {            
    document.getElementById("p_nets").innerHTML  = "NetId:" + dbitem.NetId;                
  }       
}); 

Where 'p_nets' is an HTML element in 'Index.cshtml'. The hub client (IenStateHub.js) is appended at the end of Index.cshtml as follows:

<script src="~/lib/signalr/signalr.js"></script>
<script src="~/js/IenStateHub.js"></script>

Any help to resolve this parsing issue would be highly appreciated.


Solution

  • Following method works:

    $.each(message, function(index, obj) {
        console.log( index + ": " + obj );
        $.each(obj, function( key, value ) {
            console.log( key + ": " + value );
          });
     });
    

    This is based on one of the approaches described in the link (mentioned by @Roman Koliada).

    Now I am not sure whether this is the most efficient way to access different elements in each item/object.