8

我觉得我错过了一些非常基本的东西,但是我无法使用 Knockout.js 让下拉菜单像我期望的那样工作。

我有一组要在菜单中显示的对象,我需要找到选定的选项并将其发布到服务器。我可以获取要呈现的菜单,但似乎无法获取所选项目的值。我的视图模型如下所示:

function ProjectFilterItem( name, id ) {
    this.Name = name;
    this.Id   = id;
}

function FilterViewModel() {
    this.projectFilters = ko.observableArray([
        new ProjectFilterItem( "foo", "1" ),
        new ProjectFilterItem( "bar", "2" ),
        new ProjectFilterItem( "baz", "3" )
    ]);
    this.selectedProject = ko.observable();
}

ko.applyBindings( new FilterViewModel() );

我的视图标记如下所示:

<select 
    id        = "projectMenu"   
    name      = "projectMenu"
    data-bind = "
        options:        projectFilters,
        optionsText:    'Name', /* I have to enquote the value or I get a JS error */
        optionsValue:   'Id',   /* If I put 'selectedProject here, nothing is echoed in the span below */
        optionsCaption: '-- Select Project --'
    "
></select>

<b>Selected Project:</b> <span data-bind="text: selectedProject"></span>

如何让选定的菜单项显示在跨度中,并发布到服务器?(我假设我在 span 中呈现的 observable 与我发布的相同。)我是否需要 , 中的另一个属性ProjectFilterItem,比如this.selected = ko.observable(false);?如果是这样,我将如何将其声明为值的目标?

4

1 回答 1

16

您只需要使用value绑定来绑定选定的值:

options文档中:

注意:对于多选列表,要设置选择了哪些选项,或者读取选择了哪些选项,请使用 selectedOptions 绑定对于单选列表,您还可以使用value binding读取和写入选定的选项。

在您的示例中:

<select 
    id        = "projectMenu"   
    name      = "projectMenu"
    data-bind = "
        value: selectedProject,
        options:        projectFilters,
        optionsText:    'Name',
        optionsValue:   'Id',
        optionsCaption: '-- Select Project --'
    "
></select>

请参阅演示

于 2012-11-05T21:33:09.883 回答