2013-07-17 51 views
2

我正在處理由多個下拉框組成的數據輸入窗體。下拉菜單和JSON對象並綁定選定的值

我從Web Api調用的下拉框中加載數據。返回的數據有3個值,Id,Value和Code。我將數據加載到observableArray,我可以將數據綁定到下拉框。

我遇到的問題是將下拉列表中的值加載到計算值。我從本質上得到一個NaN,當我做出選擇時,我得到了[object Object][object Object]

下面是我在做什麼的例子:

腳本

var CountryData = 
    [{"$id":"1","Code":"AMERICA","Value":"A"}, 
     {"$id":"2","Code":"FRANCE","Value":"F"}, 
     {"$id":"3","Code":"GERMANY","Value":"G"}] 

    var ProductData = 
    [{"$id":"1","Code":"Product1","Value":"1001"}, 
     {"$id":"2","Code":"Product2","Value":"1002"}, 
     {"$id":"3","Code":"Product3","Value":"1003"}] 

    var CountryViewModel = function() { 

     var self = this; 

     self.country = ko.observableArray(CountryData); 
     self.countryselected = ko.observable().publishOn("countryselected"); 
    }; 

    var ProductViewModel = function() { 

     var self = this; 

     self.product = ko.observableArray(ProductData); 
     self.productselected = ko.observable().publishOn("productselected"); 
    }; 

    var ProductCodeModel = function() { 
     this.country = ko.observable().subscribeTo("countryselected"); 
     this.product = ko.observable().subscribeTo("productselected"); 

     this.productCode = ko.computed(function() { 
      return this.country() + this.product(); 
     }, this); 
    }; 

    var masterVM = { 
     countryModel: new CountryViewModel(), 
     productModel: new ProductViewModel(), 
     productCodeModel: new ProductCodeModel() 
    }; 

ko.applyBindings(masterVM); 

和HTML

<table> 
    <tr> 
     <td><b>Country:&nbsp;</b></td> 
     <td><select data-bind="options: countryModel.country, optionsText: 'Code', value: countryModel.countryselected, optionsCaption: 'Choose...'"></select></td> 
    </tr> 
    <tr> 
     <td><b>Product:&nbsp;</b></td> 
     <td><select data-bind="options: productModel.product, optionsText: 'Code', value: productModel.productselected, optionsCaption: 'Choose...'"></select></td> 
    </tr> 
</table> 
<br /> 
<br /> 
<div>ProductCode</div> 
<div data-bind="with: productCodeModel"> 
    <span data-bind="text: productCode"></span> 
</div> 

下面是一個小提琴http://jsfiddle.net/drfiasco/A6xpX/

我已經看過映射插件,但我似乎無法得到它的工作。

回答

1

您需要訪問兩個obervables的Code字段。目前,您只是將這兩個對象拼接在一起。

this.productCode = ko.computed(function() { 
     if(this.country() && this.product()) 
      return this.country().Code + this.product().Code; 
     else 
      return "Please Make Selection Above"; 
    }, this); 

這裏是一個小提琴http://jsfiddle.net/vmysla/A6xpX/8/

+0

完美的作品!謝謝! – DrFiasco

相關問題