Reputation: 447
Trying to bind data to a dropdown list,
function EmailTemplate(data) {
var self = this;
self.etId = ko.observable(data.email_template_id);
self.etTypeId = ko.observable(data.email_template_type_id);
self.etTitle = ko.observable(data.email_template_title);
self.etContent = ko.observable(data.email_template_content);
self.etAppYear = ko.observable(data.app_year);
self.etSubject = ko.observable(data.subject);
self.etActive = ko.observable(data.active);
}
function EmailTemplateViewModel() {
var self = this;
self.ETList = ko.observableArray();
var uri = '/admin/services/EmailTemplateService.svc/EmailTemplates';
OData.read(uri, function (data, response) {
$.each(data.results, function (index, item) {
self.ETList.push(new EmailTemplate(item));
});
});
}
$(document).ready(function () {
ko.applyBindings(new EmailTemplateViewModel());
});
HTML markup:
<select data-bind="options: ETList, value:etId, optionsText: 'etTitle' "class="dropdown"></select>
When I run this I got: Uncaught Error: Unable to parse bindings. Message: ReferenceError: etIdis not defined; Bindings value: options: ETList, value:etId, optionsText: 'etTitle'
When we bind to drop down list, how should we bind the value? and after binding, how should we capture or create dropdown change event in Knockout?
Upvotes: 2
Views: 18588
Reputation: 2910
When working with <select>
options, the value
binding will determine which of the options is selected, usually you'll want an observable in your viewmodel (e.g. selectedTemplate
) that this is set to. Then this observable will automatically be mapped to the actual object from the observable array. Setting value: etId
doesn't make sense since there's no etId
in your root viewmodel.
Example: http://jsfiddle.net/antishok/968Gy/
function EmailTemplateViewModel() {
var self = this;
self.ETList = ko.observableArray();
self.selectedTemplate = ko.observable();
// ...
}
HTML:
<select data-bind="options: ETList, value:selectedTemplate, optionsText: 'etTitle'" class="dropdown"></select>
You might have intended to to optionsValue: 'etId'
which would work but is usually a less preferable approach (because the observable's value would now be set to the ID instead of the actual object)
Upvotes: 3