简体   繁体   中英

Split the data binding of KnockoutJS into table C#

I have a tag with data-bind = "value: contents" for an input tag in KnockOutJS

<input type="text" class="form-control" data-bind="value: contents" />

It displays in following format {"key1":"value1","key2":"value2"}

I'm building a table with name and value then split those keys and values separately and display in TDs

<td>
    <strong>
         <span id="textKey" data-bind="text: displayKey" />    
    </strong>
</td>

<td>
         <input id="textValue" type="text" data-bind="value: displayValue" />
</td>

Could you help me some ideas of how I can split those keys and values into Dictionary<> and into columns and rows in my case?

Thank you

If you want to use Knockout to populate a HTML table, you can use an observableArray with a foreach data binding. See here for a working JSFiddle , which uses the below code:

View Model:

var vm = {
    contents: ko.observableArray([{
        "displayKey": "Fruit",
        "displayValue": "Bananas"
    }, {
        "displayKey": "Colour",
        "displayValue": "Red"
    }, {
        "displayKey": "Car",
        "displayValue": "Ferrari"
    }])
};
ko.applyBindings(vm, document.body);

HTML:

<textarea style="width: 500px; height: 90px;"
data-bind="value: JSON.stringify(ko.toJS(contents()))"></textarea>

<table>
    <tbody data-bind="foreach: contents">
        <td> <strong>
                 <span id="textKey" data-bind="text: displayKey" />    
            </strong>
        </td>
        <td>
            <input id="textValue" type="text" data-bind="value: displayValue" />
        </td>
    </tbody>
</table>

If you do not have control over the structure of contents , you can use the conversion to array created in your previous thread like this:

Html

<table>
    <tbody data-bind="foreach: mapDictionaryToArray(contents())">
        <tr>
            <td> <span id="textKey" data-bind="text: $data.key"></span>

            </td>
            <td>
                <input id="textValue" type="text" data-bind="value: $data.value" />
            </td>
        </tr>
    </tbody>
</table>

ViewModel

var viewModel = {
        contents: ko.observable({
            "reference": "2Z94",
                "car_id": "9861"
        }),
        mapDictionaryToArray: function (dictionary) {
            var result = [];
            for (var key in dictionary) {
                if (dictionary.hasOwnProperty(key)) {
                    result.push({
                        key: key,
                        value: dictionary[key]
                    });
                }
            }
            return result;
        }
    };

jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM