无法将<select>绑定到模型值</select>

时间:2011-09-02 15:28:53

标签: c# asp.net-mvc-3 knockout.js

我看不到如何将下拉列表绑定到模型中的值。

假设我的强类型模型属于FA.Domain.Entities.Account类型。

Account有一个PersonId字段,我想将其绑定到选择下拉列表。显示视图时,我希望它反映@Model.PersonId

的值

我的代码如下:

选择标记:

<select id="People" 
        data-bind="options: allPeople, 
                   value: selectedPerson, 
                   optionsValue: 'PersonId', 
                   optionsText: 'NamePP'">
</select>

使用Javascript:

var pps = @Html.Raw(new JavaScriptSerializer().Serialize(ViewBag.PossiblePeople));

function person(PersonId, NamePP) {            
    this.CostCentreId = ko.observable(PersonId); 
    this.NamePP = ko.observable(NamePP); 
}

function PersonViewModel() {         

    this.selectedPerson = ko.observable('@Model.PersonId');

    var mapAllPeople = $.map(pps, function(item) {
        return new person(item.PersonId, item.Name)});

    this.allPeople = ko.observableArray(mapAllPeople);
}        

jQuery(document).ready(function () { 
    var viewModel = new PersonViewModel();
    alert(viewModel.selectedPerson());  // correct value
    ko.applyBindings(viewModel); 
    alert(viewModel.selectedPerson());  // undefined     
});

我做错了什么?

我添加了两个提醒,以显示selectedPerson的值。一个在绑定发生之前发生并显示正确的值,另一个发生并显示'undefined'。

1 个答案:

答案 0 :(得分:2)

我测试了一些东西,

function person(PersonId, NamePP) {            
    this.CostCentreId = ko.observable(PersonId); 
    this.NamePP = ko.observable(NamePP); 
} 

应该是:

function person(PersonId, NamePP) {            
    this.PersonId = ko.observable(PersonId); 
    this.NamePP = ko.observable(NamePP); 
}