<!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());
});
data from server:
{"Dishes":[{"Name":"Bread","Price":12.00000,"Description":"Delicious","Categories":[],"Complexs":[],"Id":1},{"Name":"Butter","Price":3.00000,"Description":"Unpalatable","Categories":[],"Complexs":[],"Id":2}]}
why ‘select’ shows me 2 items: [object Object] and [object Object]
Please sorry for my english.
You have a typo in your options databinding expression the correct property name is
optionsTextand not optionText.So you need to write
With of the misstyped property name KO can still parse the binding just won’t know which value to use as the name so it just prints out the string representation of the object.
Demo JSFiddle.