我在ASP和SignalR中编写多人游戏(Monopoly)。 我已停在页面上,其中包含一个包含游戏列表的表格。 我不知道我做得对吗:) 所以,这就是我到目前为止所做的工作,我需要帮助继续前进:
我使用空表创建了GamesList WebForm页面:
<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>
我的目标是在页面加载时填充此表。数据应由集线器提供:
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);
}
}
}
这是我在GamesList.aspx中的客户端的javascript代码:
<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>
问题是我得到了这个:“[{} {}]”。 如何将此列表从signalR传递给JS方法以填充表?
感谢。
解决:
var gamesJson = $.parseJSON(games);
for (var i = 0; i < gamesJson.length; i++) {
console.log(gamesJson[i].gameTheme);
}