Pregunta

I have the following:

    <select data-bind="options: colorOptions, optionsText: 'DisplayName', optionsValue: 'Id', value: Color.Id, optionsCaption: 'Select...'"

Where colorOptions looks like this

[
    {

        "DisplayName": "Blue",
        "Id": 22028
    },
    {
        "DisplayName": "Yellow",
        "Id": 22029
    }
]

And Color looks like this (object with observable properties):

{
    "DisplayName": "Blue",
    "Id": 22028
}

This seems to be working, except for the fact that DisplayName on the color is not updating when I make changes - only the Id is. Do I have to manually re-assign DisplayName, or can I tell knockout to replace the whole object?

¿Fue útil?

Solución

Only the value is set when you make changes with this binding handler, and since you have assigned Color.Id to the value, this is what is updated when you change the options.

The fact you have set optionsValue to be 'Id' tells the binding handler that the value comes from the Id property on the datasource, so if you want to update the whole Color proprety you need to do the following

  • Remove optionsValue: 'Id' this means that the value is set to the entire item within the array, not a single property on it
  • Update value: Color.Id to value: Color
  • You may need to change Color on your model to be an observable if it isn't already. This is only required if you want 2 way binding (i.e. the ability to set the options value by changing this property)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top