【问题标题】:Cascading Dropdowns Using Knockout.js使用 Knockout.js 级联下拉菜单
【发布时间】:2013-11-27 17:14:46
【问题描述】:

除了两件我想不通的事情之外,我能够做到这一点:

问题1:我需要同时获得以下两个,但现在只能实现一个或另一个:

  1. 选择选项需要有值和文本
  2. 模型中捕获的 selectedOption 需要返回所选选项的对象,而不仅仅是选项的值

我可以通过在我的选择标记中包含或排除以下内容来影响其中哪一项有效:

...data-bind="optionsValue = 'Id'"...

我怎样才能实现两者?

问题 2:我需要将下拉列表中的选定选项设置为我从包含用户首选值的 cookie 中检索到的对象。我的以下实现根本无法成功设置所选值。我错过了什么?

$(document).ready(function(){
    var userOption = $.cookie("userPref") == null ? undefined : JSON.parse($.cookie("userPref"));

    var model = function(){
        this.options = ko.observableArray();
        this.childOptions = ko.observableArray();
        this.selectedOption = ko.observable(userOption); //this does nothing to set the value

        this.selectedOption(userOption); //this also does nothing

        this.options.subscribe(function(){
            //this.selectedOption() returns an object if optionsValue is excluded from select databinding and returns option value if included
            $.cookie("userPref", JSON.stringify(this.selectedOption());
            this.childOptions(undefined);
            this.childOptions(this.selectedOption() ? this.selectedOption().children : []);
        }.bind(this));
    };

    var viewModel = new model();
    ko.applyBindings(viewModel);

    $.ajax({
        type: "GET",
        url: "myurl",
        success: function(data){
            viewModel.options(data);
        }
    }); 
});

<select data-bind="options: options, optionsText: 'text', optionsValue: 'Id', value: selectedOption, optionsCaption: 'Select Option'"></select>

【问题讨论】:

    标签: asp.net-mvc knockout.js


    【解决方案1】:

    您不能使用整个对象作为值,因为选项值必须是简单类型:字符串、int 等。我想您 可以 JSON 编码对象(所以它是一个字符串) 并将值设置为 that,但随后您必须在后端进行交互并将发布的字符串值解码回一个对象并以某种方式使用它。但是,所述对象将与 EF 断开连接,因此您必须从数据库中获取新对象 anyways 才能对其执行任何有意义的操作。而且,您的第二个问题与您的第一个问题相同,您不能使用完整的对象。

    这通常是使用 ids 完成的。您将选项值设为对象的 id。然后,您可以根据 cookie 中的对象 id 设置所选选项。当您到达后端时,如果您需要使用该对象,您可以通过发布的 id 获取它。其他任何事情都不是一个真正站得住脚的情况。

    【讨论】:

    • 谢谢克里斯!我没有提到我确实尝试使用简单类型方法,方法是将存储对象中的 Id 值作为字符串和整数传递给 selectedOption。没运气。此外,下拉列表不会发回任何内容,这就是为什么我要尝试使用对象本身,这些对象本身包含我需要让级联工作的所有子对象。我不需要/不想为此功能访问数据库。
    • 好吧,表单控件是用来发布的,无论您是否真的打算使用它们,所以无论如何都需要限制简单类型。也许如果您编辑了您的问题以解释您在使用 id 时遇到的问题,那么有人可能会为您提供帮助。
    猜你喜欢
    • 2014-03-20
    • 2012-05-29
    • 2018-09-20
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多