My web server returns a page with some structured markup. I need to use knockoutJS to have a markup representation at hand as a JSON object - knockout view model object.
The page basically has (right after initial loading) a <div data-bind="foreach: ExistingNamings">
that has several enclosed divs that actually hold stuff that supposed to go into the ExistingNamings array on the view model object.
Can knockout "parse" and existing markup and populate view model based on the markup provided at the moment of calling ko.applyBindings
?
A tutorial on KNJS shows the opposite - we have a data generation code in JS, and that gets pushed into an html upon applyBindings call.
P.S. My server side is ASP.NET MVC, and I've seen people suggesting http://knockoutmvc.com/ - an approach to generate initialization code for js file. This way it is "as if" view model is initialized via javascript. Is this the only way of dealing with initial data, or I indeed can parse markup?
You can directly serialize your C# models into JSON using razor like this:
or, obviously:
The only time this fails is when you have circular references, which can happen if you are dropping your Entity models directly in. If you are doing this, make a ViewModel for them, to eliminate the circular navigation properties.
Update:
To get this into your viewModel, add this to the bottom of your Razor View: