我遇到了另一个可能很小的问题。
我现在有以下结构:
[ViewModel代码]
public class ResultModel
{
public Dictionary<Person, List<Person>> dictPeople { get; set; }
public string dictPeopleJson { get; set; }
public ResultModel()
{
dictPeople = new Dictionary<Person, List<Person>>();
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
[控制器代码]
public ActionResult Index()
{
var p1 = new Person();
p1.ID = 100;
p1.Name = "John";
p1.Surname = "Smith";
var p2 = new Person();
p2.ID = 104;
p2.Name = "John";
p2.Surname = "Harvard";
var p3 = new Person();
p3.ID = 109;
p3.Name = "Kate";
p3.Surname = "Robinson";
var p4 = new Person();
p4.ID = 116;
p4.Name = "Kate";
p4.Surname = "Smith";
var p5 = new Person();
p5.ID = 130;
p5.Name = "Kate";
p5.Surname = "Jane";
List<Person> lstPerson1 = new List<Person>();
lstPerson1.Add(p1);
lstPerson1.Add(p2);
List<Person> lstPerson2 = new List<Person>();
lstPerson1.Add(p3);
lstPerson2.Add(p4);
lstPerson2.Add(p5);
var vm = new ResultModel();
vm.dictPeople.Add(new Person() {ID = 001, Name = "John", Surname = "Family"}, lstPerson1);
vm.dictPeople.Add(new Person() {ID = 002, Name = "Kate", Surname = "Family"}, lstPerson2);
vm.dictPeopleJson = JsonConvert.SerializeObject(vm.dictPeople, Formatting.Indented);
vm.dictPeople = null;
return View(vm);
}
[CSHTML代码]
<h2>Results</h2>
<table>
<tbody data-bind="template: { name: 'tblResult', foreach: dictPeopleJson() }"></tbody>
</table>
<script id="tblResult" type="text/html">
<tr>
<td data-bind="foreach: key">
<table>
<td data-bind="text: ID"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Surname"></td>
</table>
</td>
<td>
<table data-bind="foreach: value">
<td data-bind="text: ID"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Surname"></td>
</table>
</td>
</tr>
</script>
<script type="text/javascript">
var ResultModel = function(m) {
var self = this;
self.dictPeopleJson = ko.observableArray(mapDictionaryToArray(m), function(person) {
var per = new Person(person);
return per;
});
};
var Person = function(person) {
var self = this;
self.ID = ko.observable(person.Id);
self.Name = ko.observable(person.Name);
self.Surname = ko.observable(person.Surname);
};
function mapDictionaryToArray(dictionary) {
var result = [];
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
result.push({ key: key, value: dictionary[key] });
}
}
return result;
}
var data = @(Html.Raw(Json.Encode(Model)));
var dataFromServer = ko.utils.parseJson(data.dictPeopleJson);
console.log(dataFromServer);
ko.applyBindings(new ResultModel(dataFromServer));
console.log("apply binding");
</script>
我想要显示如下:
001 John Family 100 John Smith 104 John Harvard
002 Kate Family 109 Kate Robinson 116 Kate Smith ... etc
但输出只返回最后一行绑定(并且不显示字典的关键部分),
116 Kate Smith
130 Kate Jane
John系列的值丢失,数组只包含Kate家族的值
为什么会这样?转换为json字符串后,所有值都显示在字符串中,但控制台窗口仅显示kate系列(字典中的最后一项)
由于
答案 0 :(得分:0)
请使用此行进行调试
vm.dictPeople = null;
它假设不存在