1

让我们把下面作为我的 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([])};

在此背景下,我的问题是如何构建具有嵌套集合的淘汰视图模型?(如本例中的技术集合。)

寻找类似的东西..

var myViewModel = { firstName: ko.observable(''), lastName: ko.observable(''), .. };

任何帮助是极大的赞赏...

4

2 回答 2

3

在我看来,你应该使用 ko.mapping.fromJS,以防模型变得非常复杂,你不需要改变你的视图模型。

参考: http: //knockoutjs.com/documentation/plugins-mapping.html

于 2012-11-03T09:52:20.183 回答
0

这个输出非常混乱,但它说明了这个想法。这里的事情是在你的 javascript中拥有Candidate和模型,并用来调用它们的构造函数。这是小提琴。注意:如果您不打算更改模型的值,则模型不需要具有 observables 属性。TechnologyarrayMap

楷模:

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);
        }));
};
于 2012-07-03T19:53:02.853 回答