我正在进行我的第一个淘汰赛项目,可以使用一些指导。到目前为止,我可以从我的服务中在我的视图模型中填充我的主类,但是我正在尝试绑定选择列表框并且控件没有像我预期的那样绑定,尽管数据可用。虽然我现在可以获取选择列表数据来填充表单,但它没有选择正确的索引。
非常感谢您的关注!
// Initialized the namespace
var Namespace = {};
// View model declaration
Namespace.initMemberVM = function (model) {
var memberViewModel = {
Id: ko.observable(model.Id),
Married: ko.observable(model.Married),
Name: ko.observable(model.Name),
SalutationId : ko.observable(model.SalutationId),
Salutation: ko.observable(Namespace.salutations[model.SalutationId]),
Salutations: Namespace.salutations
};
return memberViewModel;
};
Namespace.initSalutations = function (model) {
console.log('called initSalutations');
Namespace.salutations = ko.mapping.fromJS(model);
};
// Bind the member
Namespace.bindData = function (model) {
// Create the view model
var viewModel = Namespace.initMemberVM(model);
ko.applyBindings(viewModel);
};
$(document).ready(function () {
Namespace.getSalutations();
Namespace.getMember(1);
});
这是ajax调用返回的数据
[{"Id":1,"Name":"Mr","IsMarried":false,"TimeStamp":"2012-11-27T21:49:10.583"},{"Id":2,"Name":"Mrs.","IsMarried":true,"TimeStamp":"2012-11-27T21:49:10.583"},{"Id":3,"Name":"Ms","IsMarried":false,"TimeStamp":"2012-11-27T21:49:10.583"},{"Id":4,"Name":"Miss","IsMarried":false,"TimeStamp":"2012-11-27T21:49:10.583"}]
这是HTML
<table>
<tbody>
<tr><td>User Id</td><td colspan="4"><label data-bind="text: Name"></label></td></tr>
<tr>
<td>Salutation</td><td><select data-bind="options: Salutations, value: Id, optionsText: 'Name'"></select></td>
</tr>
<tr>
<td></td><td>First</td><td>Middle</td><td>Last</td>
</tr>
<tr>
<td>Name</td><td><input type="text" data-bind="value: FName"></td><td><input type="text" data-bind="value: MName"></td><td><input type="text" data-bind="value: LName"></td>
</tr>
</tbody>
更新:经过进一步挖掘后,我发现我的选择没有保存正确索引的原因是 b/c 当我尝试将该值设置为我的 memberViewModel 时,Namespace.salutations 数组没有及时填充.
任何有关如何管理的指导将不胜感激!