【问题标题】:Knockout select binding value not getting set淘汰赛选择绑定值未设置
【发布时间】:2014-08-17 18:13:51
【问题描述】:

我有一个有一些值的网格,当我单击编辑时,我能够看到正在调用的函数中的值,但是当我设置需要选择的值时,它似乎没有在下拉列表中设置。我注意到的一件事是值设置为"1",但返回的数据只是1,不确定是否会导致问题

我很确定这很简单,但看不到我缺少的东西。

objUserList.selectedPartner(data.ProgramID());

这有值,但未设置选定的选项

我的代码

var objUserList;
vmUserListModel = function () {
  var self = this;
  self.UserList = ko.observableArray([]); // Populate the users
  self.Partners = ko.observableArray([]); // Populate the Partners
  self.selectedPartner = ko.observable();

  self.EditUser = function (index, data) {
     console.log(data.ProgramID()); // here I can see the value but it shows as a number with the ""
     objUserList.GetPartners();  // populate a the dropdown from an ajax call
     objUserList.selectedPartner(data.ProgramID());  // in firebug console again the value is here
     objUserList.selectedRole(data.RoleID());

    }
}

HTML

调用上述编辑函数的编辑图标处

<div data-bind="event: {click: $root.EditUser.bind($data, $index())}">
                </div>

选择绑定

<select id="Partner" data-bind="options: objUserList.Partners, optionsText: 'ProgramName', optionsValue: 'ProgramID', value: objUserList.selectedPartner, optionsCaption: 'Select'">
                </select>

我尝试使用现有的小提琴进行重现,发现相同的问题

http://jsfiddle.net/adriandcosta/h92xfd88/1/

工作代码

我正在通过 ajax 调用填充下拉列表。因此,即使在 ajax 调用返回值之前,我也试图设置选定的值。添加valueAllowUnset: true 解决了这个问题

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    小提琴的问题与您的问题无关。那是 value 绑定被添加了两次不同的值,我修复了它并且它起作用了: http://jsfiddle.net/0j2n2ay3/

    关于您的问题,所以您将select 出价到self.selectedPartner,但在函数中您正在更新objUserList.selectedPartner 的值?如果您尝试设置 self.selectedPartner(data.ProgramID()); 怎么办?

    【讨论】:

    • 这并没有什么不同,因为下拉列表是由 ajax 调用填充的。因此,即使在从 ajax 调用返回值之前,我也试图设置选定的值。我添加了valueAllowUnset 并且有效。我用工作代码更新了我的答案
    猜你喜欢
    • 2013-05-04
    • 2018-08-06
    • 2014-08-28
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    相关资源
    最近更新 更多