<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>title</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/Scripts/knockout-2.2.0.js"></script>
<script type="text/javascript" src="/Scripts/knockout.mapping-latest.js"></script>
<script type="text/javascript" src="/Scripts/jquery.form.min.js"></script>
<script type="text/javascript" src="/Scripts/myKnockout.js"></script>
</head>
<body>
<h2>Work with dishes.</h2>
<select data-bind="options:$root.dishes, optionText:'name' " multiple="multiple"></select>
</body>
</html>
myKnockout.js:
function Dish(data) {
this.name = ko.observable(data.Name);
this.price = ko.observable(data.Price);
}
function ViewModel() {
var self = this;
self.dishes = ko.observableArray();
$.getJSON("/Dishes/GetModel", function (allData) {
var mappedDish = $.map(allData.Dishes, function (item) { return new Dish(item); });
self.dishes(mappedDish);
});
}
$(document).ready(function () {
ko.applyBindings(new ViewModel());
});
来自服务器的数据:
{"Dishes":[{"Name":"Bread","Price":12.00000,"Description":"Delicious","Categories":[],"Complexs":[],"Id":1},{"Name":"Butter","Price":3.00000,"Description":"Unpalatable","Categories":[],"Complexs":[],"Id":2}]}
为什么“选择”会向我显示2个项目:[object Object]
和[object Object]
抱歉我的英语。
答案 0 :(得分:0)
您的options数据绑定表达式中有一个拼写错误,正确的属性名称是 optionsText
,而不是optionText。
所以你需要写
<select data-bind="options:$root.dishes, optionsText:'name'" multiple="multiple">
对于错误类型的属性名称,KO仍然可以解析绑定,只是不知道使用哪个值作为名称,因此它只打印出对象的字符串表示。