Hope you guys can help me. I've been working through what I'm sure is a very trivial problem but I just can't seem to get it to work. So, what I have is:
I retrieve a list from Web.API using EF
public JsonResult RetrieveAddressTypes()
{
var addressTypes = db.AddressTypeDesc.Select(s => new { AddressTypeCode = s.AddressTypeCode, AddressTypeDesc = s.AddressTypeDesc });
return Json(addressTypes.AsEnumerable(), JsonRequestBehavior.AllowGet);
}
The in my View Model I am creating an ObervableArray (AddressTypes) to store the data returned above to use in a drop down list. The binding is as follows:
<select id="inpAddressType" data-bind="options: AddressTypes, optionsText: 'AddressTypeDesc', optionsValue: 'AddressTypeCode', value: SelectAddressTypeCode"></select>
And is bound in my ViewModel using the following:
$.getJSON('api/RetrieveAddressTypes, function (data) {
AddressTypes(data);
});
I also have an observable to store the selected address type which I am hardcoding for now.
self.SelectAddressTypeCode = ko.observable(2);
This is where I am running into problems, although the bind works in that it is populating my dropdown list I just can't get it to select the value as defined in self.SelectAddressTypeCode.
It's been doing my nut over the last few days so if you could offer any help that would be great!
Cheers
==or===, but one thing to look out for here is that yourAddressTypeCodeis an integer, whereas the value which will be returned from the<select>will be a string. (2) Why the single quote marks aroundAddressTypeCodebeing passed to theoptionsValueparameter? Doesn't this tell Knockout that it should have a string literal "AddressTypeCode" as the value? Same with theoptionsTextparameter.AddressTypesan observableArray ? it should be likeself.AddressTypes(data).