Knockout Js Dictionary Display MVC
Asked Answered
C

1

7

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

Chancellorship answered 9/12, 2012 at 9:39 Comment(1)
To my mind it is the better idea to implement "mapDictionaryToArray" on the server side. Compiled code work much faster, right?Potiche
K
2

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

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

And there is one other problem with your code. When you call new ResultModel(dataFromServer) the dataFromServer is already contains the data in the right format. So you don't need m.DictJson in the ResultModel function:

var ResultModel = function(m) {
        var self = this;
        self.dictResultJson = ko.observableArray(mapDictionaryToArray(m));
};
Kerley answered 9/12, 2012 at 10:5 Comment(1)
Thanks a lot, makes perfect sense!Chancellorship

© 2022 - 2024 — McMap. All rights reserved.