0
votes

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

2

2 Answers

2
votes

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/

2
votes

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/