2017-07-05 2 views
1

Ich habe das sehr grundlegende Beispiel here gefolgt, um eine Dropdown-Liste auf einer MVC-Site zu füllen.Knockout Dropdown-Liste leer

Meine Dropdown-Liste enthält keine Elemente, obwohl ich scheinbar alles richtig gemacht habe - aber offensichtlich nicht.

mein Code hier:

<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 F12 verwendet die Länder zu überprüfen, wurden erstellt werden und sie sind - jeder sehen, wohin ich gehe falsch?

Antwort

3

Sie haben das Ansichtsmodell nicht an die Ansicht gebunden.

Am Ende des Skripts tun, um diesen

<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> 
+0

Als Seite Frage - wie würde ich es Set mit USA vorbelegt werden? – Rick

+1

@Rick überprüfen Update und auch auf diese Antwort https://StackOverflow.com/a/15589302/5233410 – Nkosi