我在使其正常工作时遇到问题。我在部分 View 中有一个表单,我想在其中填充 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>
}
这是从调用部分 View 的 View 应用绑定(bind)的脚本:
@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();
然后数据将被推送,但它仍然不会在我的部分 View 的选择字段中呈现。
最佳答案
推送data
后,你的observableArray可能不为空;为了检查它,您需要检查 self.Athletes() 的结果,因为 observableArray is a function (因此 self.Athletes 本身将显示为空数组,即使其中有元素)。
假设 data
是一组对象,每个对象代表一名运动员,它可能无法正确绑定(bind)到您的选择列表,因为您使用
self.Athletes.push(data);
由于 data 本身就是一个数组,因此您需要像这样附加 data
的元素:
self.Athletes.push.apply(self.Athletes, data);
(或者简单地将其分配为 self.Athletes(data)
,具体取决于您的要求)。
关于c# - 将数据推送到 ko.observableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20831803/