Percy
Percy

Reputation: 3125

Knockout dropdown list empty

I've followed the very basic example here to populate a dropdown list on an mvc site.

My dropdownlist doesn't have any items in it, even though I appear to have done everything correctly - but obviously I haven't.

Here's my code:

<p>
    Your country:
    <select data-bind="options: availableCountries,
                       optionsText: 'name',
                       value: selectedCountry,
                       optionsCaption: 'Choose...'"></select>

</p>
<div data-bind="visible: selectedCountry">
    <!-- Appears when you select something -->
    You have chosen a country: 
    <span data-bind="text: selectedCountry() ? selectedCountry().name : 'unknown'"></span>.
</div>

@section scripts
{
    <script type="text/javascript">

        $(function () {

        });

        // Constructor for an object with two properties
        var Country = function (name, isocode) {
            this.name = name;
            this.isocode = isocode;
        };

        var viewModel = {
            availableCountries: ko.observableArray([
                new Country("UK", "isoUK"),
                new Country("USA", "isoUSA"),
                new Country("Sweden", "isoSweden")
            ]),
            selectedCountry: ko.observable() // Nothing selected by default
        };


    </script>

}

I used F12 to check the countries were being created and they are - anyone see where I'm going wrong?

Upvotes: 1

Views: 391

Answers (1)

Nkosi
Nkosi

Reputation: 247511

You have not bound the view model to the view.

At the end of the script do this

<script type="text/javascript">

    $(function () {

    });

    // Constructor for an object with two properties
    var Country = function (name, isocode) {
        this.name = name;
        this.isocode = isocode;
    };
    var selected = new Country("USA", "isoUSA");
    var viewModel = {
        availableCountries: ko.observableArray([
            new Country("UK", "isoUK"),
            selected,
            new Country("Sweden", "isoSweden")
        ]),
        selectedCountry: ko.observable(selected) // USA selected by default
    };
    //now bind the view model to the view
    ko.applyBindings(viewModel);
</script>

Upvotes: 3

Related Questions