How to create ("map") complex types through "observables" using Knockout.js?

So, I'm learning knockout.js , and I'm a bit puzzled by how to create nested complex types in it.

For example, on my server side, my model is:

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;} } 

JSON that asp.net mvc produces something like (if I deduce the List<Person> ):

 [{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]}, {"Name":"Albert","Age":29,"Colors":{"ColorId":2,"Name":"Blue"}}] 

Now I want to map this through observables, obtained through jquery ajax. I know that FavoriteColors will be an array, but I'm a little confused about how the training will be here ...

Any help would be greatly appreciated!

UPDATE:

Can anyone help me with this? (I made a prototype, but my choice does not work)

http://jsbin.com/eqihun/3/edit#javascript,html,live

+4
source share
2 answers

look knockout display plugin

edit: your sample has been edited: http://jsbin.com/eqihun/18/edit

+4
source

solution link: 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 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> 
+2
source

Source: https://habr.com/ru/post/1388430/


All Articles