Populate knockoutJS view model object based on an

2019-05-10 08:52发布

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?

1条回答
看我几分像从前
2楼-- · 2019-05-10 09:07

You can directly serialize your C# models into JSON using razor like this:

var serverModel = @Html.Raw(Json.Encode(Model));

or, obviously:

var serverProperty = @Html.Raw(Json.Encode(Model.Property));

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:

<script type="text/javascript">
    var serverModel = @Html.Raw(Json.Encode(Model));    
    //Define KO viewModel, either here, or by including via script tag in header    
    ko.applyBinding(new ViewModel(serverModel));
</script>
查看更多
登录 后发表回答