简体   繁体   中英

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

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?

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, eg connect/disconnect events, grouping connections, authorization.

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

Hope it helps.

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.

如果Web套接字在支持HTML5的浏览器中运行,也可以使用它

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM