Send list of objects from SignalR hub to JavaScrip

2019-05-17 10:12发布

问题:

I'm writing multiplayer game (Monopoly) in ASP and SignalR. I've stopped on page which contains a table with list of games. I have no idea if I'm doing it right:) So, this is what I've done so far and I need help to move on:

I created GamesList WebForm page with empty table:

<table id="gamesTable">
  <thead>
    <tr>
      <th>#</th>
      <th>Number of players</th>
      <th>Players</th>
      <th>Theme</th>
      <th>Join<thead>
    </tr>
  </thead>
  <tbody>

  </tbody>
  <tfoot>
  </tfoot>
  
</table> 

My goal is to populate this table when page loads. Data should be provided by hub:

GamesListHub.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;

namespace Obipoly.Hubs
{
    public class GamesListHub : Hub
    {

        public List<GamesItem> games = new List<GamesItem>()
        {
            new GamesItem(2, "Theme1", "User1"),
            new GamesItem(4, "Theme3", "User2")
        }; //just for tests

        public void gamesListUpdated()
        {
            string gamesString = JsonConvert.SerializeObject(games);
            Clients.All.updateGamesList(gamesString);   //pass games list
        }

        public void addNewGame(int numberOfPlayers, string gameTheme, string hostPlayer) {
            games.Add(new GamesItem(numberOfPlayers, gameTheme, hostPlayer));
            string gamesString = JsonConvert.SerializeObject(games);
            Clients.Others.updateGamesList(gamesString);
        }

        public void getListOfGames() {
            string gamesString = JsonConvert.SerializeObject(games);
            Clients.Caller.updateGamesList(gamesString);
        }
    }
}

This is my javascript code on client side in GamesList.aspx:

<script type="text/javascript">
        $(function () {
            var gamesListHub = $.connection.gamesListHub;

            gamesListHub.client.updateGamesList = function (games) {
                console.log(games);
            };

            $.connection.hub.start().done(function () {
                gamesListHub.server.getListOfGames();
            });
        });
    </script>

The problem is I get this: "[{}{}]". How can I pass this list from signalR to JS method to populate the table?

Thanks.

SOLVED:

var gamesJson = $.parseJSON(games);
for (var i = 0; i < gamesJson.length; i++) {
    console.log(gamesJson[i].gameTheme);
}