下拉列表和JSON对象并绑定所选值 [英] Dropdowns and JSON Objects and Binding the selected value
问题描述
我正在处理由几个下拉框组成的数据输入表单.
I'm working on a Data Entry form that is made up of several drop down boxes.
我通过Web Api调用将数据加载到下拉框中.返回的数据具有3个值,即Id,Value和Code.我将数据加载到observableArray并将数据绑定到下拉框.
I load the data on the dropdown boxes from a Web Api call. The data returned has 3 values, Id, Value and Code. I load the data to a observableArray and I can bind the data to a dropdown box.
我遇到问题的地方是将下拉列表中的Value值加载到计算值中.我最初得到的是NaN,选择时得到的是[object Object][object Object]
.
Where I'm having problems is loading the Value values from the dropdowns to a computed value. I intially get a NaN and as I make selections I get [object Object][object Object]
.
这是我正在做的事的一个例子:
Here is an example of what I'm doing:
脚本
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: </b></td>
<td><select data-bind="options: countryModel.country, optionsText: 'Code', value: countryModel.countryselected, optionsCaption: 'Choose...'"></select></td>
</tr>
<tr>
<td><b>Product: </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/
我已经研究了映射插件,但似乎无法使其正常工作.
I've looked into the mapping plugin but I can't seem to get it to work.
推荐答案
您需要访问两个可观察对象的代码"字段.当前,您只是将两个对象拼接在一起.
You need to access the Code field of the two obervables. Currently you are just splicing the two objects together.
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/
这篇关于下拉列表和JSON对象并绑定所选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!