Can't bind <select> to model value
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);
}
精彩评论