【问题标题】:Why aren't the values of the dropdowns bound?为什么下拉列表的值没有绑定?
【发布时间】:2018-02-18 20:10:25
【问题描述】:

Knockout.js 是一个很好的实现 MVVM 的库。

以下最小示例使用knockout.js 绑定网格。

查看

<div id="divDecision">
  <div id="divDecisionBinding" data-bind="template: { name: 'tmplDecision' }">/div>
  <script id="tmplDecision" type="text/x-jquery-tmpl">
    <table id="tblDecision">
      <thead>
        <tr>
          <th>Candidate</th>
          <th>Decision</th>
        </tr>
      </thead>
      <tbody data-bind="foreach:decisionList" id="tbList">
        <tr>
          <td data-bind="text: candidate"></td>
          <td>
            <select data-bind="attr: { id: 'cmbDecision' + ':' + $index(), name: 'cmbDecision' + ':' + $index()}, options: viewModelDecision.decisionLookup, value: 'decision', optionsText: 'decision_desc', optionsCaption: 'Please select'"></select>
          </td>
        </tr>
      </tbody>
    </table>
  </script>
</div>

viewModelDecision(2 个成员:decisionLookup 和decisionList)

decisionLookup
0 : {decision: "N", decision_desc: "No need"}
1 : {decision: "A", decision_desc: "Approved"}
2 : {decision: "R", decision_desc: "Rejected"}
decisionList
0 : {candidate: "000000001", decision: "A" }
1 : {candidate: "000000002", decision: "N" }

脚本

var viewModelDecision;
//viewModelDecision gets loaded from a web service
viewModelDecision = result;
//Now the binding happens
ko.applyBindings(viewModelDecision, document.getElementById("divDecision"));

输出

000000001 Please select
000000002 Please select

调查结果

  1. candidate字段绑定成功
  2. 下拉列表cmbDecision:X的选项绑定成功
  3. 下拉列表cmbDecision:X 的值未绑定 - 默认选择标题“Please select”。

问题

为什么默认不选择下拉列表的值?

【问题讨论】:

    标签: javascript asp.net knockout.js


    【解决方案1】:

    value 绑定应该针对您的视图模型的可观察属性。

    您可能打算使用optionsValue 绑定来告诉knockout 使用存储在.decision 中的ID 作为选择。

    <select data-bind="options: viewModelDecision.decisionLookup, value: selectedDecision, optionsValue: 'decision', optionsText: 'decision_desc', optionsCaption: 'Please select'"></select>
    

    在你的虚拟机中:

    this.selectedDecision = ko.observable("A"); // Pre-select the 2nd item
    

    【讨论】:

    • 我部分明白你在说什么。但是,我的 viewModelDecision 来自 Web 服务 - (viewModelDecision = result)。我将更新问题以使其更清楚。然后如何在 VM 中设置 selectedDecision?
    • 您的答案适用于添加 optionsValue 和更正 value: 'decision' 到变量。我无法理解可观察的部分。如果您还可以解释如何设置 this.selectedDecision 将会很有用。
    • 您通过使用新值调用它来设置一个可观察对象。该值需要与列表中的一项决策道具相对应,以便您的选择正确更新。例如: this.selectedDecision(decisionLookup[0].decision) 选择第一个。请注意,您不需要 optionsValue 绑定;您还可以存储对对象的实际引用,而不仅仅是一个属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多