Reputation: 809
I am having an issue understanding how i'm supposed to get the selectedValue of a select (drop down) list i've binded using knockout.mapping.
heres the ajax call and mapping:
var EmailCollection;
function GetAllEmailsAjax() {
$.ajax({
url: "http://localhost:54756/api/Email",
type: "GET",
dataType: "JSON",
success: function (data) {
GetAllEmails(data);
}
});
}
function GetAllEmails(data) {
// not sure if this is 100% correct but it does seem to work as expected
if (!EmailCollection) {
EmailCollection = ko.mapping.fromJS(data);
}
ko.mapping.fromJS(data, EmailCollection);
ko.applyBindings(EmailCollection);
}
<select data-bind="options: EmailCollection, optionsText: 'Name', optionsValue: 'Id', optionsCaption: 'Choose...'"></select>
as i understand it i need to specify the value in the select data-bind attribute. So it would be something like this:
however, this would mean that selectedEmail would need to be a part of my model. However as all this is being created by knockout.mapping im unsure how i do that. I am presuming some kind of Model like the following but I am unsure on how to go about it.
var EmailViewModel = {
selectedEmail : ko.Observable(),
Emails : EmailCollection // the previous model mapped bound in a scenario like this
};
// EmailViewModel.selectedEmail() would then contain my selected value..
I'm sure once i see it on paper it will all become obvious just at the moment im struggling to work it out.
Upvotes: 0
Views: 3692
Reputation: 170
If only one email will be selected (implied since you're using a dropdown), you should create a variable to hold the selected email id. If it defaults to the first email in the collection, you'd do something like this:
var selectedEmailId: ko.observable();
...
function GetAllEmails(data) {
...
ko.mapping.fromJS(data, EmailCollection);
selectedEmailId(EmailCollection.peek().Id); //Assuming EmailCollection is an array
ko.applyBindings(EmailCollection);
}
<select data-bind="options: EmailCollection, optionsText: 'Name', optionsValue: 'Id',
optionsCaption: 'Choose...', value: selectedEmailId"></select>
selectedEmailId should then be updated any time the dropdown selection is changed.
Upvotes: 1