When first learning knockout, it took me a little while to figure out how to get data from the server and do it in a clean way. After experimenting with a few different ways of doing it, and watching Rob Conery’s excellent screencast on tekpub, I thought I would share the way I like the best. And maybe if someone else thinks they have a better way they can leave a comment.

Basically the way I do this is by taking each object I want to send to the client side and putting it into a dictionary. Then I use the ASP.NET JavaScript Serializer to convert the dictionary into some nice JSON which will be digested by the Knockout Mapping Plugin. This dictionary is then placed into the ViewBag, and I choose to call it “Data” being that this contains all the data I need initially.

 public ActionResult Index()
 {
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var ordersData = new Dictionary<String, Object>()
    {
        {"orders", GetOrders()},
        {"clients", GetClients()}
    };
    ViewBag.Data = serializer.Serialize(ordersPageData);
        
    return View();
}

Then on the client side, I am using the razor view engine and HTML.Raw() to grab the data from the ViewBag and I dump the entire thing into one javascript variable which I again call “data”. This variable I pass as a parameter into my Knockout View Model and then unwrap it using the names “orders” and “clients” which I assigned when I created the dictionary on the server side. Finally, I am using the Knockout Mapping Plugin to automatically map my data into Knockout observables.

//Dump raw data into one place 
var data = @Html.Raw(ViewBag.Data);

function ViewModel(data) {
    var self = this;
    //Unpack raw data
    self.orders = ko.mapping.fromJS(data.orders);
    self.clients = ko.mapping.fromJS(data.clients);
}
   
//initialize view model
var viewModel = new ViewModel(data);
ko.applyBindings(viewModel);
  • Nice, that’s exactly how I do it.

  • Sounouks Layst

    Which attribute should be passed to serialize.Serialize (????)