我遇到了解决这个问题的问题。我在局部视图中有一个表单,我想从ko.observableArray填充一个select字段。在我的javascript中,我可以看到我的传入数据是通过signalR返回的,但由于某种原因,它没有被推送到我的observableArray。这是我的javascript:
var AddAthleteToRosterVm = function(user) {
var self = this;
// reference the auto-generated proxy for the hub
var teamMangHub = $.connection.teamMangHub;
// Athlete and Team arrays for select list
self.Athletes = ko.observableArray();
self.Teams = new Array();
// assign athlete data
teamMangHub.client.getAthletes = function(data) {
// populate Athletes array
self.Athletes.push(data); // data is not being pushed here. Athletes array remains empty.
};
$.connection.hub.start().done(function() {
// retrieve the athletes from the server
teamMangHub.server.retrieveAthletes(user);
});
};
这是我的部分观点:
<h3 class="text-center">Add Athlete To Roster</h3>
@using (Html.BeginForm("AddAthleteToRoster", "CoachRosterManagement", FormMethod.Post,
new {@class = "text-center", id="athleteToRosterForm"}))
{
@Html.AntiForgeryToken()
<fieldset class="myFormSpace">
<legend>Athlete Info</legend>
<p>
@Html.LabelFor(x => x.InputAthleteToRoster.AthleteId)<br />
<select name="InputAthleteToRoster.AthleteId" data-bind="options: Athletes, optionsText: 'FirstName', value: 'Id', optionsCaption: 'Select'"></select>
</p>
<p>
@Html.LabelFor(x => x.InputAthleteToRoster.CoachesTeamId)<br />
@Html.DropDownListFor(x => x.InputAthleteToRoster.CoachesTeamId,
new SelectList(Enumerable.Empty<SelectListItem>()), "Select")
</p>
<button type="submit">Add Athlete</button>
</fieldset>
}
这是从调用部分视图的视图应用绑定的脚本:
@section scripts
{
<script src="~/signalr/hubs"></script>
<script src="~/Scripts/MyScripts/AddAthleteToRoster.js"></script>
<script>
var user = "@User.Identity.Name";
ko.applyBindings(new AddAthleteToRosterVm(user));
</script>
}
另一方面,当我将Athlete数组从ko.observableArray更改为标准数组时,例如:
self.Athletes = new Array();
然后数据将被推送,但它仍然不会在我的局部视图的选择字段中呈现。
答案 0 :(得分:3)
推data
后,你的observableArray可能不是空的;为了检查它,你需要检查self.Athletes()
的结果,因为observableArray is a function(所以self.Athletes本身将显示为一个空数组,即使其中有元素)。
假设data
是一个对象数组,每个对象代表一名运动员,它可能无法正确绑定到您的选择列表,因为您将所有数据推送到一个数组元素中
self.Athletes.push(data);
由于数据本身就是一个数组,因此您需要添加data
这样的元素:
self.Athletes.push.apply(self.Athletes, data);
(或者根据您的要求,可以简单地将其分配给self.Athletes(data)
。)