2
我遇到了另一個問題,可能是次要的。Knockout Js自定義字典綁定MVC
我現在以下結構:
[代碼爲視圖模型]
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>
我是tryi納克得到顯示,如:爲約翰
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
值家人都失去了,陣列只包含凱特家族的價值觀
爲什麼會發生這種情況?一旦轉換成JSON字符串正在做,正在顯示的字符串中的所有值,但控制檯窗口僅顯示了凱特家人(字典中的最後一個項目)
感謝