Javascript dropdown data dropdown

within a few days i started working with javascript knockout and bootsrap. I want to add some items to the dropdown, items from the database, and get the id (database) to click to find other data. I am adding data from controller:

success: function (data) {
            if (data != null) {
                $.each(data, function (index, element) {
                    document.pvm.CartLst.push({ Id: element.ID, Name: element.ShortName });
                });
            }
        }

      

And I will add this data to the dropdown:

_mVM.Averagepace = function (item, event) {
        var element = {cartlist: document.pvm.CartLst()}; 
        var rvm = new panelViewModel(element);
        _mVM.rapArray.push(rvm);
    }

      

In .cshtml I have this:

<ul class="dropdown-menu scrollable-menu" aria-labelledby="dropdownMenu6" data-bind="foreach: cartlist">
<li data-bind="click: document.pvm.changeSelC"><a href="#"><b data-bind="text: $data"></b></a></li></ul>

      

When the selection changes, it calls the following:

_mVM.changeSelC = function (item, event) {

            //get the id of the selected cart from the dropdownlist

            }

      

The problem is the "[object Object]" list appears in my dropdown, but it should only display the names from CartLst. And when the selection changes to get the id behind that name inside _mVM.ChangeSelC. I was looking for a different solution, but not for me. If you can help me, I would appreciate it.

+3


source to share


1 answer


This is how you usually get " [object Object]

" in a dropdown with KnockoutJS:

ko.applyBindings({ availableItems: [{Id: 1, Name: 'some item'}] });
      

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: availableItems"></select>
      

Run codeHide result




It actually makes sense if you think about it: option

bound to objects in an array. You're already hinting at this: you need to tell Knockout to use the name

elements property to display option

. This is documented in the bindingoptions

and uses a binding optionsText

, for example:

ko.applyBindings({ availableItems: [{Id: 1, Name: 'some item'}] });
      

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: availableItems, optionsText: 'Name'"></select>
      

Run codeHide result


+3


source







All Articles