I'm using Knockout MVC. In my page I render several Partial View. In each partial view i pass a model, that is submodel for main. And i'm getting an error 'Uncaught Error: You cannot apply bindings multiple times to the same element.' Here's some code.
main view
@using PerpetuumSoft.Knockout
@model UserPageViewModel
@{
var ko = Html.CreateKnockoutContext();
}
<div>
@Html.Partial("Controls/_PagePanel", Model.PanelViewModel)
</div>
@ko.Apply(Model)
Page panel partial view
@using PerpetuumSoft.Knockout
@model PagePanelViewModel
@{
var ko = Html.CreateKnockoutContext();
}
<div>
<div>
@foreach (var button in Model.Actions)
{
@ko.Html.Button(button.Id, button.ActionName, button.ControllerName, null, button.HtmlAttributes)
}
<a id="searchGridButton" class="btn" data-toggle="collapse" data-parent="#searchPanel" href="#accordionfilterContainer">Advanced search</a>
</div>
@Html.Partial("Controls/_AdvancedSearch", Model.AdvancedSearch)
</div>
@ko.Apply(Model)
Advanced Search Partial View
@using PerpetuumSoft.Knockout
@model AdvancedSearchViewModel
@{
var ko = Html.CreateKnockoutContext();
}
<div id="accordionfilterContainer" class="accordion-body collapse">
@using (ko.Html.Form(Model.ActionName, Model.ControllerName, null, new { id = "searchForm" }))
{
<div id="filterContainer" class="accordion-inner">
@using (var items = ko.Foreach(m => m.SearchCriteria))
{
<div style="display: inline-block">
<span @items.Bind.Text(m => m.Id)></span>
<br />
@items.Html.TextBox(m => m.Value, null)
</div>
}
<div style="display: inline-block">
<button type="submit" class = "@Model.HtmlAttributes">Apply filters</button>
</div>
</div>
}
</div>
@ko.Apply(Model)
Model
public class UserPageViewModel
{
public List<User> Data { get; set; }
public PagePanelViewModel PanelViewModel { get; set; }
}
public class PagePanelViewModel
{
public IEnumerable<ButtonViewModel> FilterButtons { get; set; }
public AdvancedSearchViewModel AdvancedSearch { get; set; }
public IEnumerable<ButtonViewModel> Actions { get; set; }
}
public class AdvancedSearchViewModel
{
public IList<TextBoxViewModel> SearchCriteria { get; set; }
}
I understand, that the problem is in @ko.Apply() string, but a don't understand why. Is there any way to solve the problem?
The problem is solved. It's necessary to use @ko.With() when rendering Partial view.
@ko.With() specifies the partial view what properties of submodel need to bind. And then need to delete all @ko.Apply(Model) except one in root page(main view).