Todd Davis
Todd Davis

Reputation: 6035

KnockoutJS having trouble using custom optionsText: on ko.mapping.fromJS data

I am using ASP.NET MVC, Web API and KnockOutJS to create a site. Using the Web API, I return a list of Location objects, which is grabbed via JQuery AJAX call, and stored in an observableArray.

        $.getJSON(baseLocationUri, function (data) {
            $.each(data, function (key, val) {
                self.locations.push(ko.mapping.fromJS(val));
            });
        });

An example of the data being returned might look like this (trimmed for brevity): [{"LocationId":1,"DisplayName":"Starbucks","Address":"123 Main St."}]

This is working fine, and I've used this same code in other places.

I also have a multiple select list which is bound to the observableArray. If I write the select this way, using 'DisplayName' as the optionsText:, it works fine:

<select multiple="multiple" data-bind="options: locations, selectedOptions: selectedLocations, optionsText: 'DisplayName'"></select>

Likewise, if I return DisplayName as a function, it still works:

<select multiple="multiple" data-bind="options: locations, selectedOptions: selectedLocations, optionsText: function (item) { return item.DisplayName }"></select>

BUT -- if I try to add in another parameter - it fails. All I see in the UI is "undefined".

<select multiple="multiple" data-bind="options: locations, selectedOptions: selectedLocations, optionsText: function (item) { return item.DisplayName + ' | ' + item.Address }"></select>

Just one more thing. If I remove the AJAX call and mapping, and just create an observableArray of Location objects in JavaScript, that last code works just fine.

What am I missing?

Upvotes: 4

Views: 3136

Answers (1)

Damien
Damien

Reputation: 8987

Have you tried :

 function (item) { return item.DisplayName() + ' | ' + item.Address() }

Because the ko.mapping.fromJS(val) converts DisplayName and Address into observables.

Upvotes: 5

Related Questions