我遇到了另一个 MVC/Knockout 问题。
这次它与序列化/字典集合有关。
我有以下视图模型
public class ListViewModel
{
public Dictionary<ItemViewModel, List<ItemViewModel>> Events { get; set; }
public ListViewModel()
{
Events = new Dictionary<ItemViewModel, List<ItemViewModel>>();
}
}
public class ItemViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
和cshtml文件:
<h2>Events</h2>
<div data-bind="template: { name: 'events-template', foreach: Events }"></div>
<script type="text/html" id="events-template">
<ul>
<li>
<div><span data-bind='text: Events().length'/></div>
<ul data-bind="foreach: Events">
<li><span data-bind="text: $data"> </span></li>
</ul>
</li>
</ul>
</script>
<script type="text/javascript">
var ListViewModel = function(model) {
var self = this;
self.Events = ko.observableArray(ko.utils.arrayMap(model.Events, function(itemViewModel) {
var item = new ItemViewModel(itemViewModel);
return item;
}));
};
var ItemViewModel = function(itemViewModel) {
var self = this;
self.Name = ko.observable(itemViewModel.name);
self.Id = ko.observable(itemViewModel.Id);
};
$(function() {
var data = @(Html.Raw(Json.Encode(Model)));
ko.applyBindings(new ListViewModel(data));
});
</script>
它似乎卡在 var data = @(Html.Raw(Json.Encode(Model)));
错误消息提到“类型通用字典......不支持字典的序列化/反序列化,键必须是字符串或对象。”