让我们将下面作为我的MVC模型类:
public class Candidate
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int Experience { get; set; }
public List<Technology> Technologies { get; set; }
}
public class Technology
{
public string Technology { get; set; }
public int ExperinceInMonths { get; set; }
}
现在,我有一个web api方法,它返回这个模态数据:
public class CandidateController : ApiController
{
// GET api/Candidate
public IEnumerable<Candidate> Get()
{
CandidateServiceClient client = new CandidateServiceClient();
List<Candidate> candidateData = client.GetCandidateData();
if (candidateData == null || candidateData.Count() == 0)
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NoContent));
return candidateData.AsEnumerable();
}
...
使用Knockout让我说我有这样的javascript:
$.get(url, function (result) {
candidateViewModel.candidates(result);
ko.applyBindings(candidateViewModel);
});
});
var candidateViewModel = { candidates: ko.observableArray([])};
有了这个背景,我的问题是如何构建具有嵌套集合的knockout viewmodel? (如本例中的技术收集。)
寻找类似......
的东西var myViewModel = { firstName:ko.observable(''), lastName:ko.observable(''), .. };
非常感谢任何帮助...
答案 0 :(得分:3)
在我看来,你应该使用ko.mapping.fromJS,以防模型变得非常复杂,你不需要改变你的视图模型。
答案 1 :(得分:0)
这个输出超级凌乱,但它说明了这个想法。这里的事情是在您的javascript中使用Candidate
和Technology
模型,并使用arrayMap
来调用其构造函数。这是the fiddle。注意:如果您不打算更改其值,则模型不需要具有observables属性。
型号:
var Technology = function(name, monthsExperience){
this.name = ko.observable(name);
this.monthsExperience = ko.observable(monthsExperience);
};
var Candidate = function(data){
this.firstName = ko.observable(data.FirstName || '');
this.lastName = ko.observable(data.LastName || '');
this.email = ko.observable(data.Email || '');
this.experience = ko.observable(data.Experience || '');
this.technologies = ko.observableArray(ko.utils.arrayMap(data.Technologies || [],
function(i){
return new Technology(i.Technology, i.ExperinceInMonths);
}));
};
主视图模型:
var App = function(initialData){
this.candidates = ko.observableArray(ko.utils.arrayMap(initialData|| [],
function(i){
return new Candidate(i);
}));
};