I am testing out the very awesome Knockoutjs. I am facing a peculiar problem.
I found a similar question: Binding initial/default value of dropdown (select) list, but it is not helping, as mine are cascading lists.
I make my initialModel as follows, using data from server.
var initialModel = @Html.Raw(JsonConvert.SerializeObject(Model)) ;
Then I define my viewModel as follows.
var viewModel = {
evaluationGroups :ko.observableArray(initialModel.EvaluationGroups),
SelectedEvaluationArea:ko.observable(initialModel.selectedEvaluationArea ? initialModel.selectedEvaluationArea.Id :null ),
SelectedEvaluationGroup :ko.observable(initialModel.selectedEvaluationGroup)
}
Now, I want cascading select
lists. Hence my binding is as under.
<fieldset>
<legend>Evaluation Group and Area</legend>
<p>
<select id="EvaluationGroupId" name="EvaluationGroupId" data-bind='options: evaluationGroups, optionsText:"Title", value:SelectedEvaluationGroup, optionsCaption: "Select Group..."'></select>
</p>
<p>
<select id="EvaluationAreaId" name="EvaluationAreaId" data-bind='options: SelectedEvaluationGroup()? SelectedEvaluationGroup().EvaluationAreas:null, optionsValue: "Id", optionsText:"Title", value:SelectedEvaluationArea, optionsCaption: "Select Area..."'></select>
</p>
</fieldset>
The problem is, I am unable to extract the initial value from my server data. If I see, the value of viewModel.SelectedEvaluationGroup
, when the page has just loaded, with default values, I see undefined
. However, if I see initialModel.selectedEvaluationGroup
, it is the full object, as expected. What am I doing wrong? Is this not the correct way to initialize Knockout's observables?
Maybe you have forgotten to run the applyBindings command?
i.e.
Update
I have had a play with your jsfiddle. Seems it is happy to bind to initial values when it is manually set to ones from the main array.
http://jsfiddle.net/ZMvNM/5/