I am stuck on something quite basic I believe, therefore I require some expertise to help me achieve this task.
I have a dictionary which takes an integer and string as values in order to store a list of results (which I will show below). My View Model and Controller have this code, that post the data as a JSON String to the Knockout:
[Code for ViewModel]
public class ResultModel
{
public Dictionary<int, string> dictResult { get; set; }
public string dictResultJson { get; set; }
public ResultModel()
{
dictResult = new Dictionary<int, string>();
}
}
[Code for cshtml file]
<h2>Results</h2>
<table>
<tbody data-bind="template: { name: 'tblResult', foreach: dictResultJson() }"></tbody>
</table>
<script id="tblResult" type="text/html">
<tr>
<td data-bind="value: key"></td>
<td data-bind="value: value"></td>
</tr>
</script>
<script type="text/javascript">
var ResultModel = function(m) {
var self = this;
self.dictResultJson = ko.observableArray(mapDictionaryToArray(m.DictJson));
};
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.dictResultJson);
console.log(dataFromServer);
ko.applyBindings(new ResultModel(dataFromServer));
console.log("apply binding");
</script>
In my cshtml file I am parsing the returned object from the MVC Controller and converting it into an array. Now the problem is that it is not displaying any data, but the variable dataFromServer contains proper data. It has this data:
Object {1: "Kate", 3: "Alex", 4: "Jane"}
Now, how am I supposed to loop this json Result in order to display it in a table format, such as
Table
1 Kate
3 Alex
4 Jane
Thanks in advance
Jesmond