1

In my javascript;

var tenderStatusChoices = '@Html.Raw(Model.TenderStatusChoices)';

I get the following data;

var tenderStatusChoices = '
    [{
        "Disabled": false,
        "Group": null,
        "Selected": true,
        "Text": "Open",
        "Value": "Open"
    }, {
        "Disabled": false,
        "Group": null,
        "Selected": false,
        "Text": "Successful",
        "Value": "Successful"
    }, {
        "Disabled": false,
        "Group": null,
        "Selected": false,
        "Text": "Unsuccessful",
        "Value": "Unsuccessful"
    }]';

I cannot use this JSon to populate a combo box in knockout, when I do I get the following error;

"The argument passed when initializing an observable array must be an array, or null, or undefined."

So how do I convert this Json string to an array that ko will understand?

The code that populates the combo is as follows;

<select id="TenderStatus" data-bind="
    options: tenderStatusChoices,
    optionsText: 'Text',
    optionsValue: 'Value',
    value: status">
</select>

var temp = '@Html.Raw(Model.TenderStatusChoices)';
var tenderStatusChoices = JSON.stringify(eval("(" + temp + ")"));

var Tender = function () {
    this.tenderId = ko.observable("@Model.Tender.TenderId");
    this.title = ko.observable("@Html.Raw(Model.Tender.Title)");
    this.estimateNumber = ko.observable("@Model.Tender.EstimateNumber");
    this.status = ko.observable("@Model.Tender.Status");
    this.tenderStatusChoices = ko.observableArray(tenderStatusChoices);
};

ko.applyBindings(Tender);
1

1 Answer 1

1

You need to use the mapping plugin or loop through your data manually.

this.tenderStatusChoices = ko.observableArray(JSON.parse(temp));

Or use mapping plugin

this.tenderStatusChoices = ko.observableArray(ko.mapping.toJS(temp));
Sign up to request clarification or add additional context in comments.

3 Comments

I would like the mapping solution to work, although it does not make any difference. I am not clear what the difference is between ToJS or fromJS. With the JSON.parse method, the application is falling over because: 'tenderStatusChoices' is undefined. I cannot see why this is.
toJS converts observableArray to plan array of objects while fromJSON is vise versa
The JSON.parse solution works. For that reason I give your answer a tick. The mapping solution does not work for some reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.