Big data

Description

The sample demonstrates lazy data loading using the following construction: @ko.LazyApply. Main page is loaded first and then additional ajax query loads all data (controller method with getting initial data is set in parameters of LazyApply method).

Live example

Start

Content: loading...

End

Model

public class BigDataModel
{
    public string Key { get; set; }
    public List<int> Items { get; set; }

    public void LoadData()
    {
        Key = "Key " + new Random().Next();
        Items = new List<int>();
        for (int i = 0; i < 100; i++)
            Items.Add(i);

        Thread.Sleep(2000);
    }
}

Razor

@using PerpetuumSoft.Knockout
@model KnockoutMvcDemo.Models.BigDataModel
@{
  var ko = Html.CreateKnockoutContext();
}
<h3>Start</h3>
Content:
@ko.Html.Span(m => m.Key)
@ko.Html.Span("loading...").Visible(m => !Convert.ToBoolean(m.Key))
<h3>End</h3>

@ko.LazyApply(Model, "InitialData", "BigData")

Controller

public class BigDataController : BaseController
{
    public ActionResult Index()
    {
        InitializeViewBag("Big data");
        return View();
    }

    public ActionResult InitialData(BigDataModel model)
    {
        model.LoadData();
        return Json(model);
    }
}

Html (autogenerated)

<h3>Start</h3>
Content:
<span data-bind="text : Key"></span>
<span data-bind="visible : !Key()">loading...</span>
<h3>End</h3>

<script type="text/javascript"> 
$(document).ready(function() {
$.ajax({ url: '/BigData/InitialData', type: 'POST', success: function (data) {
var viewModel = ko.mapping.fromJS(data); 
ko.applyBindings(viewModel);
}, error: function (error) { alert('There was an error posting the data to the server: ' + error.responseText); } });
});
</script>