Dictionary for Knockout Js Display MVC

I’m stuck in something completely ordinary, I think, so I need some experience to help me achieve this goal.

I have a dictionary that takes an integer and a string as values ​​to save a list of results (which I will show below). My view model and controller have this code that sends data as a JSON string for 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 parse the returned object from MVC Controller and convert it to an array. Now the problem is that it does not display any data, but the dataFromServer variable contains the correct data. It has the following data:

Object {1: "Kate", 3: "Alex", 4: "Jane"}

Now, how should I loop this json Result to display it in a table format like

Table

1 kate

3 alex

4 jane

Thank you in advance

Jesmond

+6
source share
1 answer

If you want to display the values ​​in the table as text, you should use text binding instead of value

 <tr> <td data-bind="text: key"></td> <td data-bind="text: value"></td> </tr> 

And there is another problem with your code. When you call new ResultModel(dataFromServer) , dataFromServer already contains the data in the correct format. Therefore, you do not need m.DictJson in the ResultModel function:

 var ResultModel = function(m) { var self = this; self.dictResultJson = ko.observableArray(mapDictionaryToArray(m)); }; 
+2
source

All Articles