简体   繁体   中英

Knockout ajax foreach loop not working

I am trying to bind a array of data to my knockout template, but when I do try to bind it I get

 Uncaught ReferenceError: Unable to parse bindings.
 Bindings value: foreach: attributes
 Message: attributes is not defined

Below is the ajax call I will use in order to get my data back. I have replaced the self.attributes with the expected data to be returned just to make it testable in jsfiddle.

$.ajax({
    url: '/api/MyApi',
    type: 'GET',
    dataType: 'json',
    data: {
        DamageId: urlCat
    },
    success:
           function (data) {
               ko.applyBindings(new DetailViewModel(currentDamage, fakeHistData, data));

           },
    error: function () {
    }
});


function DetailViewModel(data, damHist,attrs) {
var self = this;
self.details = data;
self.attributes  = '{[{"Id": 258,"Value": "Yes","AttributeId": 195,"AttributeName": "FurtherDamage","AttributeText": "Is the condition causing further damage to the property?"},{"Id": 259,"Value": "Zombie Attack","AttributeId": 196,"AttributeName": "Description","AttributeText": "Enter a description for the damage"}]}'
self.damHistory = ko.observableArray(damHist);
}

here is my HTML

<div class="itemAttributesContainer topBorder">
    <h4>Attributes</h4>
    <table id="attributeTable" data-bind="foreach: attributes">
        <tr>
            <td>
                <span class="attrQuestion" data-bind="text: AttributeText + ': '" />
                <span data-bind="text: Value" />
            </td>
        </tr>
    </table>
</div>

http://jsfiddle.net/2Tp4E/

Your fiddle is not working anyhow please check by adding this code. You need knockout mapping plugin for this.

Html:

    <table id="attributeTable" data-bind="foreach: attributes">
            <tr>
                <td>
                    <span data-bind="text: AttributeText() + ': '" />
                    <span data-bind="text: Value()" />
                </td>
            </tr>
        </table>

View Model:

    self.attributes = ko.mapping.fromJSON('[{"Id": 258,"Value": "Yes","AttributeId": 195,"AttributeName": "FurtherDamage","AttributeText": "Is the condition causing further damage to the property?"},{"Id": 259,"Value": "Zombie Attack","AttributeId": 196,"AttributeName": "Description","AttributeText": "Enter a description for the damage"}]')

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