Initializing viewmodel with default data from server
How do we populate data in the knockoutjs view model on the first call to the page? That is, when the View is rendered the first time.
My server View Model class contains a list of objects. I want the knockoutjs view model property to be initialize开发者_运维知识库d with this value.
I tried the below code but it fails with the following error:
A circular reference was detected while serializing an object of type.
This is my code:
var mylist = @Html.Raw(Json.Encode(Model.list));
var viewModel = {
list: ko.observableArray(myList),
};
The standard drop down list works with the same property. Seems like a serialization issue?
<div class="editor-field">
@Html.DropDownListFor(model => model.list, new SelectList(Model.list, "id", "name"), "-- select --")
</div>
You should use a view model which doesn't have circular references otherwise you will not be able to JSON serialize it (Json.Encode(Model.list)
). I suppose that this Model.list
property is a collection of some objects which have circular references between them. You will have to remove properties from your view model that are causing those circular references if you want to be able to JSON serialize your model.
精彩评论