传回枚举字典时所选值不起作用

Selected value not working when passing back enum dictionary

我正在使用敲除数据绑定创建一个选项列表。基本上在我的服务器端我有一个枚举

public enum CarType
{
    Saloon = 1,
    Hatch = 2,
    Convertable = 3,
    SUV = 4
}

这基本上是在服务器端创建成字典,然后发送回客户端。

所以上面的枚举将return作为一个带有键和值的对象发送给客户端。

我的视图模型是这样的:

this.carName= ko.observable();
this.carType = ko.observable();  

我的选项绑定如下:

<select class="form-control" data-bind="options: $root.carTypes, optionsText: 'value', optionsValue: 'key', value: carType"></select>

所以基本上当我按下编辑按钮时,这个视图将在第一轮正确呈现。但是,如果我取消编辑页面并重新打开它,那么它会选择选项列表中的第一个元素。

不确定我是否做错了什么,或者 knockout 与字典的行为是否不同?

汽车类型对象 returned 是下面示例中的字典元素数组

[{key="1", value="Saloon"}, {key="2", value="Hatch"}  .......

我不确定我是否理解你的问题。您是否希望避免选择第一项?如果是这样,请查看文档中的 optionsCaptionhttp://knockoutjs.com/documentation/options-binding.html#parameters

optionsCaption

Sometimes, you might not want to select any particular option by default. But a single-select drop-down list usually starts with some item selected, so how can you avoid preselecting something? The usual solution is to prefix the list of options with a special dummy option that just reads “Select an item” or “Please choose an option” or similar, and have that one selected by default.

This easy to do: just add an additional parameter with name optionsCaption, with its value being a string to display. For example:

<select data-bind='options: myOptions, optionsCaption: "Select an item...", value: myChosenValue'></select>

KO will prefix the list of items with one that displays the text “Select an item…” and has the value undefined. So, if myChosenValue holds the value undefined (which observables do by default), then the dummy option will be selected. If the optionsCaption parameter is an observable, then the text of the initial item will update as the observable’s value changes.