开发者

Can't bind <select> to model value

开发者 https://www.devze.com 2023-04-02 05:49 出处:网络
I can\'t see how to bind a drop down list to the value in the model. Let\'s say my strongly typed Model is of type FA.Domain.Entities.Account.

I can't see how to bind a drop down list to the value in the model.

Let's say my strongly typed Model is of type FA.Domain.Entities.Account.

Account has a PersonId field, that I want to bind to a select drop down list. When the view is displayed, I want it to reflect the value of @Model.PersonId.

My code is as follows:

Select tag:

<select id="People" 
        data-bind="options: allPeople, 
                   value: selectedPerson, 
                   optionsValue: 'PersonId', 
                   optionsText: 'Name开发者_StackOverflowPP'">
</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     
});

What am I doing wrong?

I have put in two alerts, to show the value of selectedPerson. One goes before the binding happens and displays the correct value, the other goes after and shows 'undefined'.


I tested some things,

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

Should be:

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

精彩评论

暂无评论...
验证码 换一张
取 消