我正在使用Knockout MVC。在我的页面中,我渲染了几个部分视图。在每个局部视图中,我传递一个模型,即main的子模型。而且我收到错误'未捕获错误:您无法多次将绑定应用于同一元素。'这是一些代码。
主视图
@using PerpetuumSoft.Knockout
@model UserPageViewModel
@{
var ko = Html.CreateKnockoutContext();
}
<div>
@Html.Partial("Controls/_PagePanel", Model.PanelViewModel)
</div>
@ko.Apply(Model)
页面面板局部视图
@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)
高级搜索局部视图
@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)
模型
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; }
}
据我所知,问题出现在@ ko.Apply()字符串中,但是不明白为什么。有什么方法可以解决这个问题吗?
答案 0 :(得分:1)
问题解决了。在渲染部分视图时,必须使用@ ko.With()。
<div>
@using (var subModel = ko.With(m => m.PanelViewModel))
{
@Html.Partial("Controls/_PagePanel", Model.PanelViewModel)
}
</div>
@ ko.With()指定部分视图子模型需要绑定的属性。然后需要删除所有@ ko.Apply(Model),除了根页面(主视图)中的一个。