How to pass an array from SignalR server and present the result using Knockout
I'm playing around with SignalR and KnockoutJS and can't seem to find an easy way to get an array from a database exposed using MVC4 framework.
I have no problem sending a single object from the server, but when I try to send an array, I get stuck. Hopefully someone with more experience can spot the obvious mistakes I am making and show how this should be done (JavaScript is not my forte). The problem, as I understand it, is the mapping of the data transferred from the server. Any help is greatly appreciated!
SignalR Hub (orders - simple table with id and name)
public class feedHub : Hub
{
private dataContext db = new dataContext();
public void GetAll()
{
var orders = db.orders.ToArray();
Clients.getData(orders);
}
}
Simple HTML code for submitting orders;
<div id="Demo">
<div data-bind="foreach: orders">
<div data-bind="html: Id"></div>
<div data-bind="html: Name"></div>
</div>
</div>
JavaScript
<script type="text/javascript">
var viewModel = {
orders: ko.observableArray(orders)
};
ko.applyBindings(viewModel, $("#Demo")[0]);
$(function () {
// Client side version of the feebHub class
var hubcon = $.connection.feedHub;
// getData called from server
hubcon.getData = function (data) { viewModel.orders(data) };
// Start connection and call getAll
$.connection.hub.start(function () { hubcon.getAll(); });
});
</script>
source to share
A few points:
- Just use
ko.observableArray()
, i.e. no parameter - Place the call
ko.applyBindings
inside your finished function, eg. just before you get the hub link
This should be enough to make it work. At least it works in this fiddle that I based on your code.
One more point though ... you are passing plain JSON objects in KO (i.e. inside your observable array). This is similar to data binding in C # to some classes that do not implement INotifyPropertyChanged. IOW binding will work correctly once and changes to objects will never be reflected in the UI. If you want SignalR to feed changes to your objects, then they must have visible properties and you might want to look into the KO display plugin .
source to share