简体   繁体   中英

Databinding with Knockout JS not working

I'm trying to bind my JSON object to a HTML div but none of the bindings seem to work. This is my current try on the subject. But I have tried using the template binding already. That resulted in an undefined error , but the object is correctly loaded because i always get it in the console.

$(document).ready(function () {
var submissionViewModel = new SubmissionModel();
submissionViewModel.getSubmission().done(function () {
    ko.applyBindings(submissionViewModel, document.getElementById("submission"));
})
});

var SubmissionModel = function () {
var self = this;
//self.loading = ko.observableArray();
self.Submission = ko.observable(null);

self.getSubmission = function () {
    // Let loading indicator know that there's a new loading task that ought to complete
    //self.loading.push(true);

    return $.getJSON('/Submission/GetSubmission',
        function (data) {
            console.log("submission loading")
            console.dir(data);

            self.Submission = ko.mapping.fromJSON(JSON.stringify(data));
        }
    );
}
}

HTML

<div id="submission" data-bind="with: Submission">
<span data-bind="text: SubmissionTitle"></span>
</div>

JSON

"{"
SubmissionID":"1be87a85-6d95-43aa-ad3c-ffa047b759a5",
"SubmissionTitle":"nog wat sliden",
"SubmissionDescription":"////",
"SubmissionFile":"TESTFILE  ",
"CreatedOn":"2015-09-02T21:10:54.913",
"SubmissionPoolID":"5af408f5-515c-4994-88dd-dbb2e4a242a2",
"SubmissionTypeID":1,
"CreatedBy":"a028a47d-3104-4ea4-8fa6-7abbb2d69bbd
"}"

I have been chewing on this problem for a few days now an I can't seem to get it to work. Could any of you point me in the right direction ?

In java-script to decode object inside string you need to use JSON.parse and make sure your object is not structured in such way double quote inside double quote .

viewModel:

var json = '{"SubmissionID":"1be87a85-6d95-43aa-ad3c-ffa047b759a5","SubmissionTitle":"nogwatsliden","SubmissionDescription":"--","SubmissionFile":"TESTFILE  ","CreatedOn":"2015-09-02T21:10:54.913","SubmissionPoolID":"5af408f5-515c-4994-88dd-dbb2e4a242a2","SubmissionTypeID":1,"CreatedBy":"a028a47d-3104-4ea48fa67abbb2d69bbd"}'
var ViewModel = function () {
    this.Submission = ko.observable();
    this.Submission(ko.mapping.fromJS(JSON.parse(json)));
    //you can also use ko.mapping.fromJSON(json) as jeroen pointed out   
};
ko.applyBindings(new ViewModel());

working sample here

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