Jules Wensley
Jules Wensley

Reputation: 111

KnockoutJs Observable Arrays and Dropdownlists

I'm new to KnockoutJs and I wonder if anyone can help with this.

I have a viewmodel, populated from a Mvc3 controller, bound to a dropdown and this is working fine.

I have additional data stored in the "platforms" observableArray, and I would like this data to be displayed in textboxes, dependant on the selected value in the dropdown.

Here is my code so far:-

<script type="text/javascript">
    $(document).ready(function () {
        var sampleSubmission = function () {
            this.selectedPlatform = ko.observable();
            this.platforms = ko.observableArray();

            this.showSearch = ko.observable(false);
            this.craftText = ko.observable();
            this.showSerialNumber = ko.observable(0);

            this.selectedPlatform.subscribe(function (platformId) {





            } .bind(this));
        };

        var sampleSubmissionViewModel = new sampleSubmission();
        ko.applyBindings(sampleSubmissionViewModel);

        //Load the platforms
        $.ajax({
            url: '@Url.Action("GetPlatforms", "Home")',
            type: 'GET',
            success: function (data) {
                sampleSubmissionViewModel.platforms(data);
            }
        });
    });  

</script>

Does anyone have any ideas how I achieve this?

Thanks in advance.

Upvotes: 4

Views: 2717

Answers (1)

John Papa
John Papa

Reputation: 22338

You can bind the dropdown list's value to the selectedPlatform, like this:

<select data-bind="options: platforms, value: selectedPlatform, optionsText: 'name'"></select>

I modified your code and took some best guesses at what you wanted to do and created a sample. Here is the fiddle: http://jsfiddle.net/johnpapa/DVXH7/

Upvotes: 5

Related Questions