【发布时间】:2014-01-17 00:52:37
【问题描述】:
我只是想填充几个我用 jquery 呈现的选择标签。
来自服务器的传入模型:
public class DepthChartsVm
{
public List<DepthChartModel> ReturnDepthCharts {get;set;}
}
public class DepthChartModel
{
public Team Team {get;set;}
public int SportId {get;set;}
}
public class Team
{
// various properties
public List<AthleteInfo> AthleteInfo {get;set;}
public List<positions> BasketBallPositonList {get;set;}
}
public class AthleteInfo
{
// various properties
List<DepthChart> DepthChartPositions {get;set;}
}
public class DepthChart
{
// various properties
prop ...etc
}
public class Positions
{
// various properties
prop ... etc.
}
HTML:
<div class="col-sm-4">
<label for="teamDropDown" class="text-center">Teams</label>
<select id="teamDropDown" data-bind="options: depthVm.ReturnDepthCharts, value: selectedTeam,
optionsText: function(item){return item.Team.FullName},
optionsCaption: 'select'"></select>
<p data-bind="if: selectedTeam">
<strong>Sport: </strong> <span data-bind="text: selectedTeam().Team.Sport"></span><br />
<strong>Season: </strong> <span data-bind="text: selectedTeam().Team.Season"></span>
</p>
</div>
<!--Athletes-->
<div class="col-sm-4">
<div data-bind="if: selectedTeam">
<h3 class="text-center">Athletes</h3>
<div data-bind="foreach: selectedTeam().Team.AthleteInfo">
<p>
<strong>Name: </strong><span data-bind="text: FirstName()
+ ' ' + LastName()"></span>
</p>
<div data-bind="foreach: DepthChartPositions()">
<p>
<input class="hidden" name="InputUpdateDepthChart.RosterId"
data-bind="value: RosterId"/>
Position: <select name="InputUpdateDepthChart.PositionId"
data-bind="options: $root.selectedTeam().Team.BasketBallPostionList,
optionsText: 'Position', value: PositionId, optionsValue: 'Id'"></select>
String: <select name="InputUpdateDepthChart.StringId"
data-bind="options: DepthStrings, optionsText: 'String',
value: StringId, optionsValue: 'Id'"></select>
</p>
<p>
<button data-bind="click: $root.addPosition">Add Position</button>
</p>
</div>
</div>
</div>
</div>
</div>
// script that serializes the model and passes it to knockout
<script>
// json encode incoming model
var depthModelData = @Html.Raw(JsonConvert.SerializeObject(Model))
// update depth chart vM
ko.applyBindings(new UpdateDepthChartVm(depthModelData),
document.getElementById('updateDepthChartForm'));
</script>
查看模型:
var UpdateDepthChartVm = function (model) {
var self = this;
self.depthVm = ko.mapping.fromJS(model);
// selected team
self.selectedTeam = ko.observable();
// add position
self.addPosition = function () {
self.selectedTeam.Team.AthleteInfo.DepthChartPositions.push(new depthChartPosition());
};
function depthChartPosition(values) {
values = values || {};
var model = {
RosterId: ko.observable(values.RosterId),
PositionId: ko.observable(values.PositionId),
StringId: ko.observable(values.StringId),
};
return model;
}
};
基本上,当用户希望添加另一个位置时,我会尝试即时复制第一段。 jquery 确实可以使用选择标签呈现新段落,但是选择字段是空的,因为它们与我的视图模型之间似乎没有绑定。除此之外,我的视图模型正在工作。我在这里错过了什么?
【问题讨论】:
标签: jquery asp.net-mvc knockout.js