I'm creating an edit form for a user, the roles of the user are not selected by default in a multiple select.
There are 2 application roles: "Administrator" and "Moderator". The sample user has 1 role "Administrator". This one is not selected by default.
http://jsfiddle.net/jgT8s/4/
html:
<form data-bind="with: user">
<select id="selectRoles"
data-bind="options: $root.allRoles, selectedOptions: Roles, optionsText: 'Name', optionsValue: 'Id'"
multiple="true"
size="5">
</select>
</form>
js:
var User = function () {
var self = this;
self.Id = ko.observable(1337);
self.Username = ko.observable('pietpaulusma');
self.Roles = ko.observableArray([{ Id: 1, Name: 'Administrator' }]);
};
function UserViewModel() {
var self = this;
self.user = ko.observable(new User());
self.allRoles = ko.observableArray([{ Id: 1, Name: 'Administrator' }, { Id: 2, Name: 'Moderator' }]);
}
ko.applyBindings(new UserViewModel());
UPDATE created an dependentObservable and mapped that one to selectedOptions
self.RoleIds = ko.dependentObservable(function () {
return ko.utils.arrayMap(self.Roles(), function (role) {
return role.Id;
});
});
working version: http://jsfiddle.net/jgT8s/5/
The problem is that Roles
contains "full" object whereas it should contain only the value part:
self.Roles = ko.observableArray([1]);
Take a look here: http://jsfiddle.net/Vkda5/
Knockout needs to compare selected options by values, which is Id
in this case: optionsValue: 'Id'
. And you're passing an array of Role
objects. You need to pass array of Id
instead:
var User = function () {
...
self.Roles = ko.observableArray([1]);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With