Combine context

Description

Sample demonstrates construction of nested contexts featuring access to properties that are on different levels.

Live example

CombineContext


Model

public class CombineContextSubItemModel
{
    public string Name { get; set; }
}

public class CombineContextItemModel
{
    public string Caption { get; set; }
    public List<CombineContextSubItemModel> SubItems { get; set; }
}

public class CombineContextModel
{
    public string Key { get; set; }
    public List<CombineContextItemModel> Items { get; set; }
}

Razor

@using PerpetuumSoft.Knockout
@model KnockoutMvcDemo.Models.CombineContextModel
@{
  var ko = Html.CreateKnockoutContext();
}
<h2>CombineContext</h2>
@using (var items = ko.Foreach(m => m.Items))
{
  using (var subItems = items.Foreach(m => m.SubItems))
  {
  @subItems.Html.Span(m => ko.Model.Key + " " + items.Model.Caption + " " + m.Name)<br />
  }
}

@ko.Apply(Model)

Controller

public class CombineContextController : BaseController
{
    public ActionResult Index()
    {
        InitializeViewBag("Combine context");
        var model = new CombineContextModel
          {
              Key = "Global",
              Items = new List<CombineContextItemModel>
        {
          new CombineContextItemModel
            {
              Caption = "Item 1",
              SubItems = new List<CombineContextSubItemModel>
                {
                  new CombineContextSubItemModel {Name = "SubItem1-1"},
                  new CombineContextSubItemModel {Name = "SubItem1-2"},
                  new CombineContextSubItemModel {Name = "SubItem1-3"},
                }
            },
          new CombineContextItemModel
            {
              Caption = "Item 2",
              SubItems = new List<CombineContextSubItemModel>
                {
                  new CombineContextSubItemModel {Name = "SubItem2-1"},
                  new CombineContextSubItemModel {Name = "SubItem2-2"},
                  new CombineContextSubItemModel {Name = "SubItem2-3"},
                }
            }
        }
          };
        return View(model);
    }
}

Html (autogenerated)

<h2>CombineContext</h2>
<!-- ko foreach: Items -->
<!-- ko foreach: $data.SubItems -->
<span data-bind="text : (((($parents[1].Key() + &#39; &#39;) + $parent.Caption()) + &#39; &#39;) + $data.Name())"></span><br />
<!-- /ko -->
<!-- /ko -->

<script type="text/javascript"> 
var viewModelJs = {"Key":"Global","Items":[{"Caption":"Item 1","SubItems":[{"Name":"SubItem1-1"},{"Name":"SubItem1-2"},{"Name":"SubItem1-3"}]},{"Caption":"Item 2","SubItems":[{"Name":"SubItem2-1"},{"Name":"SubItem2-2"},{"Name":"SubItem2-3"}]}]};
var viewModel = ko.mapping.fromJS(viewModelJs); 
ko.applyBindings(viewModel);
</script>