2012-10-23 54 views
0

我有一個視圖模型,看起來像這樣:顯示視圖模型作爲下拉

var teamViewModel = { 
     teams: ko.observableArray([]), 
     clearTeams: function(){ 
      this.teams.removeAll(); 
     }, 
     addTeam: function (id, name, isChecked) { 
      t = new team(id, name, isChecked); 
      this.teams.push(t); 
     } 
    }; 

,我讓所有的球隊是這樣的:

function GetAvailableTeams() { 

     var jqxhr = 
     $.getJSON('http://localhose/Service.svc/GetTeamsAll', 
      function (data) { 
       teamViewModel.clearTeams(); 
       $.each(data.GetTeamsAllResult, 
        function (key, val) { 
         teamViewModel.addTeam(val.TeamId, val.TeamName, true); 
        }); 
       ko.applyBindings(teamViewModel, document.getElementById("teamNameLabel")); 
      }) 
    } 

我如何數據綁定選擇有TeamName作爲名稱,TeamId作爲Value。

這裏是我的嘗試,但它說的ID不能被識別:

<select id="teamNameLabel" onclick="nextfunction()" date-theme="f" data-bind="options: teams, optionsText: 'name', value: 'id'"></select>

我也想了ID返回的onchange()

回答

1

您應該使用optionsValue,而不是結合的value,如果你想商店只是id

<select id="teamNameLabel" data-bind="options: teams, optionsText: 'name', optionsValue: 'id'"></select> 

當您使用value綁定你不應該包裝屬性名稱與quotes。在這種情況下,屬性將存儲整個team對象。

+0

太棒了,太棒了!另一件事,當頁面加載時沒有optionCaption或默認值,id像optionCaption被初始化爲name [1],但改變爲上次選擇的任何內容(它當前執行後者) – Mike