如何通过“可观察对象”创建(映射)复杂类型Knockout.js
How to create ("map") complex types through "observables" with Knockout.js?
所以,我正在学习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获得。我知道FavoriteColors
将是一个数组,但我有点困惑的事情将如何锻炼在这里…
任何帮助都将非常感激!
更新:
有谁能帮我一下吗?(我做了一个原型,但我的选择不起作用)http://jsbin.com/eqihun/3/edit javascript、html、生活
看看knockout mapping插件
链接到解决方案: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>
相关文章:
- 如何在映射数组中添加换行符
- ng映射方向备选方案
- 无法通过数组映射绑定
- ReactJS映射:如何仅在url变量不为空时呈现html链接
- 使用Scala Play Framework视图中的键检索映射值
- 在Redux中,我应该在哪里编写复杂的异步流
- 淘汰映射;不起作用
- 将复杂对象从angular js传递到web api,它总是返回404
- dropdown.js中的复杂事件处理
- 您有更好的动态方式来缩短复杂的代码jquery吗
- 相当复杂的Regex
- 用Javascript重新格式化复杂文本日期字符串的更好方法
- 映射数组ES6时考虑空值
- Lodash映射并返回唯一
- 如何通过“可观察对象”创建(映射)复杂类型Knockout.js
- 用于嵌套复杂对象的淘汰映射
- Jquery从输入映射复杂数组
- 为区域构建具有可选和不同背景(颜色和图像填充)的复杂图像映射
- 带有复杂对象的 KnockoutJS 映射插件
- 淘汰:将映射扩展到复杂的 JSON