为什么下拉列表的值不受限制?

时间:2017-09-10 13:28:16

标签: javascript asp.net knockout.js

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”默认选中。
  4. 问题

    为什么默认情况下没有选择下拉列表的值?

1 个答案:

答案 0 :(得分:1)

value绑定应定位到您的viewmodel的可观察属性。

您可能打算使用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