So if your Controller Action returns a Model with pre-populated values, how do you make KnockoutJS aware of them?
E.g.:
@Html.TextBoxFor(m => m.Title, new { data_bind="value: title"} )
however, on $(document).ready() where I bind knockout.js ViewModel, this value isn’t yet populated:
$(document).ready({
var viewModel = {
title: ko.observable($("#Title").val()) // too early for this?!
}
ko.applyBindings(viewModel);
});
How do you make KnockoutJS work with MVC’s model binding?
One workaround I found was to set the JavaScript variable in my Razor View, like so:
<script>
var strTitle = '@Model.Title';
</script>
and than use it in the Knockout model binding. That works, but I hate it. What if your form has like hundreds of fields? You don’t want as many JavaScript variables in your page.
Am I missing the obvious here?
This seems similar to this question. Normally you would set your view model by converting @Model to JSON in a script:
You could also create your own binding handler that will initially load the view model based on control values. This new
myvaluehandler basically calls the existingvaluehandler, except it updates the view model from the initial control value on init.Then when you call ko.applyBindings, your observable will be set based on the control’s value initially:
SAMPLE FIDDLE