I’m on my first knockout project and could use a little guidance. So far I can populate my main class in my view model from my service, but I’m trying to bind the select list box and the control isn’t binding as I expect, although the data is available. While I now can get the select list data to populate the form, it isn’t picking the proper index.
Your attention is greatly appreciated!
// 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);
});
here is the data returned from the ajax call
[{"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"}]
and here is the 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>
update: after a little further digging I’ve observed that the reason why my select is not holding the correct index is b/c the Namespace.salutations array isn’t populated in time when I’m trying to set that value to my memberViewModel.
Any guidance on how to manage that would be appreciated!
For those who are having similar issues, here is the remaining bits of code that you may find useful..
Again, if you missed it in the comments, I updated my first call to the service to bring back the data for my controllers as well as for my member. I’ll adjust this approach later so that reference data is stored for later use separately, but for now…