0

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

6
  • A couple of points which might help to debug the problem: (1) I'm not sure how Knockout matches a selected value, whether it uses == or ===, but one thing to look out for here is that your AddressTypeCode is an integer, whereas the value which will be returned from the <select> will be a string. (2) Why the single quote marks around AddressTypeCode being passed to the optionsValue parameter? Doesn't this tell Knockout that it should have a string literal "AddressTypeCode" as the value? Same with the optionsText parameter. Commented May 27, 2015 at 10:13
  • share us a sample json of your ajax return so its easy to check . any console errors ? cheers Commented May 27, 2015 at 11:29
  • Is AddressTypes an observableArray ? it should be like self.AddressTypes(data) . Commented May 27, 2015 at 11:32
  • Ok, so I've changed the binding syntax to what is used here Commented May 28, 2015 at 7:33
  • Here is come sample Json from Ajax call: [{"AddressTypeCode":1,"AddressTypeDesc":"Principal Business"},{"AddressTypeCode":2,"AddressTypeDesc":"Registered Office"}] Commented May 28, 2015 at 7:33

1 Answer 1

1

If I understand your problem, it's happening because you are setting the value of SelectAddressTypeCode before the return of the ajax call. This might help you:

//your view model
self.SelectAddressTypeCode = ko.observable();

//your ajax call function
$.getJSON('api/RetrieveAddressTypes, function (data) {
    self.AddressTypes(data);
    self.SelectAddressTypeCode('2'); //set the selectedAddressTypeCode as string, after the populating of addressType.
});

For a real scenario this may be a problem because you can't hardcode the assigned value of the select element. In this case you should create a handler to populate the select element with the selected value while the ajax has not returned. Like this:

ko.bindingHandlers.populateInitialValue = {
            init: function (element, valueAccessor, allBindingsAccessor) {
                var bindings = allBindingsAccessor(),
                    options = ko.utils.unwrapObservable(bindings.options),
                    optionsValue = bindings.optionsValue,
                    value = ko.utils.unwrapObservable(bindings.value),
                    initialValue;

                if (options && !options.length) {
                    if (optionsValue) {
                        initialValue = {};
                        initialValue[optionsValue] = value;
                    }
                    else {
                        initialValue = value;
                    }

                    bindings.options.push(initialValue);
                }
            }
        };

HTML:

<select id="YourSelectId" name="YourSelectId" data-bind="populateInitialValue: true, options: yourOptions, optionsText: 'text', optionsValue: 'value', optionsCaption: '- Select -', value: yourSelectedValue"></select>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.