如何实现网页的实时数据

时间:2014-09-14 01:43:20

标签: c# asp.net ajax asp.net-web-api signalr

(这是一个Q / A风格的问题,旨在成为那些提出类似问题的人的首选资源。很多人似乎偶然发现了这样做的最佳方式,因为他们不会这样做。了解所有选项。许多答案都是特定于ASP.NET的,但AJAX和其他技术确实在其他框架中具有等价物,例如socket.io和SignalR。)

我有一个我在ASP.NET中实现的数据表。我想实时或接近实时地显示页面上此基础数据的更改。我该怎么做呢?

我的模特:

public class BoardGame
    {
    public int Id { get; set;}
    public string Name { get; set;}
    public string Description { get; set;}
    public int Quantity { get; set;}
    public double Price { get; set;}

    public BoardGame() { }
    public BoardGame(int id, string name, string description, int quantity, double price)
        {
        Id=id;
        Name=name;
        Description=description;
        Quantity=quantity;
        Price=price;
        }
    }

代替这个例子的实际数据库,我只是将数据存储在Application变量中。我将在我的Global.asax.cs的Application_Start函数中播种它。

var SeedData = new List<BoardGame>(){
    new BoardGame(1, "Monopoly","Make your opponents go bankrupt!", 76, 15),
    new BoardGame(2, "Life", "Win at the game of life.", 55, 13),
    new BoardGame(3, "Candyland", "Make it through gumdrop forrest.", 97, 11)
    };
Application["BoardGameDatabase"] = SeedData;

如果我使用的是Web表单,我会使用转发器显示数据。

<h1>Board Games</h1>
        <asp:Repeater runat="server" ID="BoardGameRepeater" ItemType="RealTimeDemo.Models.BoardGame">
            <HeaderTemplate>
                <table border="1">
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Description</th>
                        <th>Quantity</th>
                        <th>Price</th>
                    </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td><%#: Item.Id %></td>
                    <td><%#: Item.Name %></td>
                    <td><%#: Item.Description %></td>
                    <td><%#: Item.Quantity %></td>
                    <td><%#: Item.Price %></td>
                </tr>
            </ItemTemplate>
            <FooterTemplate></table></FooterTemplate>
        </asp:Repeater>

将数据加载到后面的代码中:

protected void Page_Load(object sender, EventArgs e)
    {
    BoardGameRepeater.DataSource = Application["BoardGameDatabase"];
    BoardGameRepeater.DataBind();
    }

如果这是使用Razor的MVC,它只是对该模型的简单预示:

@model IEnumerable<RealTimeDemo.Models.BoardGame>
<h1>Board Games</h1>
<table border="1">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Quantity)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
    </tr> 
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Id)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Quantity)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
    </tr>
} 
</table>

让我们使用Web窗体添加一个用于添加数据的页面,以便我们可以实时观察数据更新。我建议您创建两个浏览器窗口,以便同时查看表单和表格。

<h1>Create</h1>
<asp:Label runat="server" ID="Status_Lbl" /><br />
Id: <asp:TextBox runat="server" ID="Id_Tb" /><br />
Name: <asp:TextBox runat="server" ID="Name_Tb" /><br />
Description: <asp:TextBox runat="server" ID="Description_Tb" /><br />
Quantity: <asp:TextBox runat="server" ID="Quantity_Tb" /><br />
Price: <asp:TextBox runat="server" ID="Price_Tb" /><br />
<asp:Button runat="server" ID="SubmitBtn" OnClick="SubmitBtn_Click" Text="Submit" />

背后的代码:

protected void SubmitBtn_Click(object sender, EventArgs e)
    {
    var game = new BoardGame();
    game.Id = Int32.Parse(Id_Tb.Text);
    game.Name = Name_Tb.Text;
    game.Description = Description_Tb.Text;
    game.Quantity = Int32.Parse(Quantity_Tb.Text);
    game.Price = Int32.Parse(Price_Tb.Text);
    var db = (List<BoardGame>)Application["BoardGameDatabase"];
    db.Add(game);
    Application["BoardGameDatabase"] = db;
    //only for SignalR
    /*var context = GlobalHost.ConnectionManager.GetHubContext<GameHub>();
    context.Clients.All.addGame(game); */           
    }

4 个答案:

答案 0 :(得分:19)

SignalR

这是我最乐于分享的答案,因为它代表了一种更清晰的实施方案,重量轻,在当今的移动(数据限制)环境中运行良好。

多年来,有多种方法可以提供实时&#34;将数据从服务器推送到客户端(或推送数据的外观)。快速短轮询(类似于我的基于AJAX的答案),Long PollingForever FrameServer Sent EventsWebSockets是用于实现此目的的不同传输机制。 SignalR是一个抽象层,能够根据客户端和服务器的功能选择合适的传输机制。使用SignalR最好的部分是它很简单。您不必担心传输机制,编程模型也很容易理解。

我要定义一个SignalR集线器,但只需将其留空。

public class GameHub : Hub
    {
    }

当我将数据添加到&#34;数据库&#34;时,我将运行下面的代码。如果你读了这个问题,你会看到我在&#34;创建&#34;中评论了它。形成。你想要取消注释。

var context = GlobalHost.ConnectionManager.GetHubContext<GameHub>();
context.Clients.All.addGame(game);

这是我的网页代码:

<h1>SignalR</h1>
        <asp:Repeater runat="server" ID="BoardGameRepeater" ItemType="RealTimeDemo.Models.BoardGame">
            <HeaderTemplate>
                <table border="1">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Name</th>
                            <th>Description</th>
                            <th>Quantity</th>
                            <th>Price</th>
                        </tr>
                    </thead>
                    <tbody id="BoardGameTblBody">
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td><%#: Item.Id %></td>
                    <td><%#: Item.Name %></td>
                    <td><%#: Item.Description %></td>
                    <td><%#: Item.Quantity %></td>
                    <td><%#: Item.Price %></td>
                </tr>
            </ItemTemplate>
            <FooterTemplate></tbody></table></FooterTemplate>
        </asp:Repeater>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="Scripts/jQuery-1.6.4.min.js"></script>
        <script src="Scripts/jquery.signalR-2.1.1.min.js"></script>
        <script src="signalr/hubs"></script>
        <script type="text/javascript">
            var hub = $.connection.gameHub;
            hub.client.addGame = function (game) {
                $("#BoardGameTblBody").append("<tr><td>" + game.Id + "</td><td>" + game.Name + "</td><td>" + game.Description + "</td><td>" + game.Quantity + "</td><td>" + game.Price + "</td></tr>");
            };
            $.connection.hub.start();
        </script>

背后的代码:

protected void Page_Load(object sender, EventArgs e)
        {
        BoardGameRepeater.DataSource = Application["BoardGameDatabase"];
        BoardGameRepeater.DataBind();
        }

请注意这里发生了什么。当服务器调用context.Clients.All.addGame(game);时,它会为连接到GameHub的每个客户端执行已分配给hub.client.addGame的功能。 SignalR负责为我配置事件,并自动将服务器上的game对象转换为客户端上的game对象。最重要的是,每隔几秒就没有来回的网络流量,所以它非常轻巧。

优点:

  • 网络流量非常清晰
  • 易于开发,但仍然灵活
  • 不会发送带有请求的视图状态
  • 不会连续轮询服务器。

注意,您可以在客户端上为editedGame添加一个功能,以便将更改的数据轻松推送到客户端(同样用于删除)。

答案 1 :(得分:3)

定时器/ UpdatePanel的

如果您使用的是Web窗体,则可以使用名为UpdatePanel的控件。 UpdatePanel能够异步刷新页面的各个部分,而不会导致整个页面的回发。结合asp:Timer,您可以随时更新表格。这是代码:

<asp:ScriptManager runat="server" />
        <h1>Board Games (using Update Panel)</h1>
        <asp:Timer runat="server" ID="UP_Timer" Interval="5000" />
        <asp:UpdatePanel runat="server" ID="Game_UpdatePanel">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="UP_Timer" EventName="Tick" />
            </Triggers>
            <ContentTemplate>
                <asp:Repeater runat="server" ID="BoardGameRepeater" ItemType="RealTimeDemo.Models.BoardGame">
                    <HeaderTemplate>
                        <table border="1">
                            <tr>
                                <th>Id</th>
                                <th>Name</th>
                                <th>Description</th>
                                <th>Quantity</th>
                                <th>Price</th>
                            </tr>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <tr>
                            <td><%#: Item.Id %></td>
                            <td><%#: Item.Name %></td>
                            <td><%#: Item.Description %></td>
                            <td><%#: Item.Quantity %></td>
                            <td><%#: Item.Price %></td>
                        </tr>
                    </ItemTemplate>
                    <FooterTemplate></table></FooterTemplate>
                </asp:Repeater>
            </ContentTemplate>
        </asp:UpdatePanel>

背后的代码:

    protected void Page_Load(object sender, EventArgs e)
        {
        BoardGameRepeater.DataSource = Application["BoardGameDatabase"];
        BoardGameRepeater.DataBind();
        }

让我们来谈谈这个是如何工作的。每隔5秒钟,计时器将触发一个Tick事件。这是使用UpdatePanel注册为异步回发服务器,因此发生部分回发,整个页面生命周期再次运行,因此它重新加载页面加载事件上的数据,然后更新UpdatePanel的内容模板的全部内容从服务器生成数据。我们来看看网络流量的外观:

+5s Client => Server | Run the page lifecycle, send me the contents of the ContentPanel.
Server => Client | Here's the entire contents of the ContentPanel.
+10s Client => Server | Run the page lifecycle, send me the contents of the ContentPanel.
Server => Client | Here's the entire contents of the ContentPanel.
+15s Client => Server | Run the page lifecycle, send me the contents of the ContentPanel.
Server => Client | Here's the entire contents of the ContentPanel.

优点:

  • 易于实施。只需添加一个计时器,一个脚本管理器,并将转发器包装在更新面板中。

缺点:

  • Heavy:每次请求都会将ViewState发送到服务器。如果禁用ViewState(无论如何都应该这样做),可以减轻这种影响。
  • 重:数据是否已更改,您每隔5秒就会通过线路发送所有数据。这是一大块带宽。
  • 慢:每次部分回发需要很长时间,因为所有数据都会通过网络传输。
  • 难以使用:当您开始添加更多功能时,正确处理部分回发可能会非常棘手。
  • 不聪明:即使之前的请求没有完成,也会因为计时器而继续回复。
  • 不聪明:没有简单的方法来处理网络中断。

答案 2 :(得分:2)

AJAX轮询,更好的实施

与其他基于AJAX的答案类似,您可以不断轮询服务器。但这一次,我们将回复一个ID数据列表,而不是回应显示的数据。客户端将跟踪它已在数组中检索到的数据,然后当它看到添加了新ID时,它将向服务器发出单独的GET请求以获取数据。

这是我们的页面代码:

<h1>Board Games (AJAX Polling Good)</h1>
        <table id="BoardGameTbl" border="1">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Description</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody id="BoardGameTblBody">
            </tbody>
        </table>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script type="text/javascript">
            var loadedGames = [];
            function getListOfGames() {
                $.ajax({
                    type: "GET",
                    url: "api/GamesApi/GetGameIds",
                    dataType: "json"
                })
                .done(function (data) {
                    for (i = 0; i < data.length; i++) {
                        if (loadedGames.indexOf(data[i]) == -1) {
                            loadedGames[loadedGames.length] = data[i];
                            getGame(data[i]);
                        }
                    }
                    setTimeout(getListOfGames, 5000);
                });
            }
            function getGame(id) {
                $.ajax({
                    type: "GET",
                    url: "api/GamesApi/GetGame/" + id,
                    dataType: "json"
                })
                .done(function (game) {
                    $("#BoardGameTblBody").append("<tr><td>" + game.Id + "</td><td>" + game.Name + "</td><td>" + game.Description + "</td><td>" + game.Quantity + "</td><td>" + game.Price + "</td></tr>");
                });
            }
            getListOfGames();
        </script>

以下是Web API控制器:

namespace RealTimeDemo.Controllers
{
public class GamesApiController : ApiController
    {
    [Route("api/GamesApi/GetGameIds")]
    public IEnumerable<int> GetGameIds()
        {
        var data = HttpContext.Current.Application["BoardGameDatabase"] as List<BoardGame>;
        var IDs = data.Select(x => x.Id);
        return IDs;
        }

    [Route("api/GamesApi/GetGame/{id}")]
    public BoardGame GetGame(int id)
        {
        var data = HttpContext.Current.Application["BoardGameDatabase"] as List<BoardGame>;
        return data.Where(x => x.Id == id).SingleOrDefault();
        }
    }

现在,这是一个比我基于其他AJAX的答案和Timer / UpdatePanel答案更好的实现。由于我们每5秒钟只发送一次ID,因此对网络资源的影响要小得多。处理没有网络连接情况,或者在加载新数据时执行某种通知也是相当简单的,例如抛出noty

优点

  • 不向请求发送视图状态。
  • 不执行整个页面生命周期
  • 作为轮询的一部分,只有ID通过网络发送(如果您发送了带有请求的时间戳,并且只回复了自时间戳以来已更改的数据,则可以改进ID)。只从数据库中检索新对象。

缺点 - 我们仍在轮询,每隔几秒钟生成一次请求。如果数据不经常变化,则会不必要地占用带宽。

答案 3 :(得分:1)

AJAX轮询,执行不力

如果您使用的是MVC或Web窗体,则可以实现一种称为AJAX轮询的技术。这将不断向服务器发送AJAX请求。服务器将发送包含最新数据的响应。实施起来非常简单。您不必使用jQuery来使用AJAX,但它会让它变得更容易。此示例将使用Web API作为服务器端功能。 Web API类似于MVC,它使用路由和控制器来处理请求。它是ASMX Web Services的替代品。

这是网络表单代码,但它与MVC代码非常相似,因此我将省略:

<h1>Board Games (AJAX Polling Bad)</h1>
        <table id="BoardGameTbl" border="1">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Description</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody id="BoardGameTblBody">
            </tbody>
        </table>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script type="text/javascript">
            function getData() {
                $.ajax({
                    type: "GET",
                    url: "api/GamesApi/GetGameData",
                    dataType: "json"
                })
                .done(function (data) {
                    $("#BoardGameTblBody").empty();
                    for (i = 0; i < data.length; i++) {
                        $("#BoardGameTblBody").append("<tr><td>" + data[i].Id + "</td><td>" + data[i].Name + "</td><td>" + data[i].Description + "</td><td>" + data[i].Quantity + "</td><td>" + data[i].Price + "</td></tr>");
                    }
                    setTimeout(getData, 5000);
                });
            }
            getData();
        </script>

这是对Web API的请求。 API返回所有游戏的JSON表示。

public class GamesApiController : ApiController
    {
    [Route("api/GamesApi/GetGameData")]
    public IEnumerable<BoardGame> GetGameData()
        {
        var data = HttpContext.Current.Application["BoardGameDatabase"] as List<BoardGame>;
        return data;
        }
    }

此方法的总体结果类似于Timer / UpdatePanel方法。但它不会随请求发送任何视图状态数据,也不会执行长页面生命周期过程。你也不必跳舞,检测你是否在回发中,或者你是否在部分回发中。所以我认为这是对Timer / UpdatePanel的改进。

但是,此方法仍然存在Timer / UpdatePanel方法的主要缺点之一。您仍然可以通过每条AJAX请求通过线路发送所有数据。如果你看看我的其他基于AJAX的答案,你会看到一种更好的方法来实现AJAX轮询。

优点

  • 不会向请求发送视图状态。
  • 不执行整个页面生命周期

缺点

  • 每隔几秒生成一次请求
  • 响应包括所有数据,即使它没有更改