Pushing data from an ASP.NET MVC Controller to a V

2019-05-03 23:22发布

问题:

I'm building the back end to a site which will have multiple "widgets" on the front end which need to update in real time.

Right now I simply have a load method which populates all the widgets with data, on page load obviously. My question is how to handle the real time aspect of further updates.

I thought of having just multiple ajax calls, which could query a service every second or so, and return the latest data, but that seems inefficient.

Is there a way to "push" data to a View from a Controller?

回答1:

It depends on how often the data on the front end needs to be updated. Most pages aren't going to need constant updating. I don't know that there is a "best practice" threshold, but I think a good starting point would be 15-20 second updates using Ajax. Make your Ajax calls fast and lean - maybe just return blank if there are no updates. If you need faster updates than that, look into something called long polling. Long polling is basically where you trigger an ajax call to the server, and the connection sits open until there is data to be sent. Long polling will take more server resources, because you will have open connections and threads running while they are waiting for data to be ready. With ASP.NET you'll also have to worry about killing long polling threads, because by default those threads wouldn't be killed when the browser closes connection (for example if someone navigates away from the page.)



回答2:

maybe you can have a look at this project : https://github.com/SignalR/SignalR

ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time.

SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients' browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.

(Excerp from http://signalr.net/ )

Hope it helps.



回答3:

I think your best bet is to periodically poll the server:

$(document).ready(function() {

    setTimeout("getUpdate()", 30000);

    function getUpdate()
    {
        // Make an ajax call here
    }
});

This will ask for an update every 30 seconds.



回答4:

You can also use Web Sockets, if its running in a browser that support HTML5