MetalMad
MetalMad

Reputation: 446

Knockout mapping select json not work

I'm new to automapper KO. I have this code:

 var jData = [
                    { "Id": 2, "Name": "A" },
                    { "Id": 3, "Name": "B" },
                    { "Id": 4, "Name": "C" }]
            };
        var viewModel = ko.mapping.fromJSON(JSON.stringify(jData));
        ko.applyBindings(viewModel);

This code works:

<div data-bind="foreach : $data">
            <input type="text" data-bind='value: Name' />
            <br />
        </div>

but if I want to select via a map:

 <select id="prova" data-bind='options: $data, optionsText: "Name", optionsValue: "Id"    , value: Id'></select>

I received this error

Enable to parse bindings. Message: ReferenceError: 'Id' is undefined; Bindings value: options: $data, optionsText: "Name", optionsValue: "Id" , value: Id

What's wrong? thanks L

Upvotes: 0

Views: 2367

Answers (2)

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

The root cause of the issue is that your view model doesn't contain Id property. You should add it. I would implemented something like this:

 var jData = [
                    { "Id": 2, "Name": "A" },
                    { "Id": 3, "Name": "B" },
                    { "Id": 4, "Name": "C" }]

function ViewModel(){
   var self = this;

   self.list = ko.mapping.fromJSON(JSON.stringify(jData));
   self.Id = ko.observable();
}

var viewModel = new ViewModel();
ko.applyBindings(viewModel);

HTML:

<select id="prova" data-bind='options: list, optionsText: "Name", optionsValue: "Id"    , value: Id'></select>

Here is working fiddle: http://jsfiddle.net/ardr8/

Upvotes: 2

Scorpion-Prince
Scorpion-Prince

Reputation: 3634

The issue is with the value:Id binding, the Id needs to be in "". Also, the value binding should be used to set the selected value in the dropdown, just setting it to Id will always select the one with value 1.

<select id="prova" data-bind='options: $data, optionsText: "Name", optionsValue: "Id", value: "Id"'></select>

Check the jsfiddle here http://jsfiddle.net/uVfgx/

Upvotes: 2

Related Questions