2017-07-05 55 views
1

我已經按照最基本的示例here填充mvc網站上的下拉列表。敲除下拉列表空

我的下拉列表中沒有任何項目,儘管我似乎已經做了一切正確 - 但顯然我沒有。

這裏是我的代碼:

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

} 

我用F12檢查正在創建的國家,他們是 - 任何人都看到我要去哪裏錯了嗎?

回答

3

您尚未將視圖模型綁定到視圖。

在腳本結束做到這一點

<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

作爲一個方面的問題 - 我將如何設置它與美國的預先填充? – Rick

+1

@Rick檢查更新,並看看這個答案https://stackoverflow.com/a/15589302/5233410 – Nkosi