所以,我正在学习 knockout.js ,我对如何在其中创建嵌套复杂类型感到有点困惑。
例如,在我的服务器端,我的模型是:
class Person {
public string Name {get; set;}
public int Age {get; set;}
public List<Colors> FavoriteColors {get; set;}
}
class Color {
public int ColorId {get; set;}
public string Name {get; set;}
}
asp.net mvc输出的JSON就像(如果我输出List<Person>
类型):
[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},
{"Name":"Albert","Age":29,"Colors":{"ColorId":2,"Name":"Blue"}}]
现在我想通过Jquery Ajax获取的observable来映射它。我知道FavoriteColors
会是一个数组,但我对这里的事情会有点困惑......
非常感谢任何帮助!
更新
任何人都可以帮我这个吗? (我做了一个原型,但我的选择不起作用)
答案 0 :(得分:4)
编辑:您的示例已修改:http://jsbin.com/eqihun/18/edit
答案 1 :(得分:2)
链接到解决方案:here
$(document).ready(function(){
//document.writeln(data[0].Colors[0].Name);
//if I map anything to ko.observable, it would be sent through ko.toJSON... so that means that Color stuff should NOT be mapped, especially because that's not what MVC is asking, but rather List<Colors>...
var Color = function (id, name) {
var self = this;
self.colorId = id;
self.name = name;
};
function viewModel() {
var self = this;
self.Name = ko.observable("Bert");
self.Age = ko.observable('12');
self.FavoriteColors = ko.observableArray([
new Color(1, "Blue"),
new Color(2, "Red"),
new Color(3, "White")
]);
}
ko.applyBindings(new viewModel());
});
HTML:
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://raw.github.com/SteveSanderson/knockout/master/build/output/knockout-latest.debug.js" type="text/javascript"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<p>Name: <input type="text" data-bind="value: Name" name="Name"></p>
<p>Age: <input type="text" data-bind="value: Age" name="Name"></p>
<select data-bind="options: FavoriteColors, optionsText: 'name', value: 'colorId', optionsCaption: 'Choose...'"></select>