【发布时间】:2014-01-16 21:10:03
【问题描述】:
我在让它工作时遇到问题。我在部分视图中有一个表单,我想在其中填充来自 ko.observableArray 的选择字段。在我的 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();
然后数据将被推送,但它仍然不会在我的局部视图的选择字段中呈现。
【问题讨论】:
-
如何确定 Athletes observableArray 为空?您尝试推送的
data是什么样的? -
当我单步执行代码时,数组为空。数据是一个复杂的对象。它是一个包含各种字段的对象数组,这些字段可能包含也可能不包含其他对象。
-
要访问 observableArray,您必须为其添加括号,因为它实际上是一个函数:
self.Athletes().length。 -
@Michael Best 我应该在代码中的哪个位置进行更改。
标签: c# javascript asp.net-mvc knockout.js signalr