使用knockout在下拉列表中预选值

时间:2017-07-06 16:35:15

标签: knockout.js

我有多个10个下拉列表显示在页面中。我正在使用knockout来构建页面。基本上我有一个'网站的集合' obseravablearray。内部'网站'数组我有一个'用户'这是一个可观察的阵列。 '用户'显示为下拉列表。我需要在下拉列表中预先选择一个值。但它不起作用。我无法在下拉列表中看到所选值。如有任何帮助,请通知我。我不会硬编码下拉列表的任何id值,因为下拉列表的显示是动态的。

Below is the sample code using knockout  (aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication6.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <script src="Scripts/jquery-3.0.0.js"></script>
    <script src="Scripts/bootstrap.js"></script>
    <script src="Scripts/knockout-3.4.0.js"></script>
    <script src="primarySetup.js"></script>
</head>
<body>
        <form id="frmPrimarySiteUser">
        <div class="container">
            <div class="row">
                <span>Setup </span>
            </div>
            <div class="row">
                <table class="table-bordered table-condensed table-hover table-responsive" id="tblEncode">
                    <thead>
                        <tr>
                            <th>Site Name</th>
                            <th>User Id</th>
                        </tr>
                    </thead>
                    <tbody data-bind="foreach: PrimarySiteUsers">
                        <tr>
                            <td><span data-bind="text: SiteName"></span></td>
                            <td><select name="ddlUsers" data-bind="options: UserParam, selected: 'SelectedUserId', optionsText: 'UserName', optionsValue: 'UserId', optionsCaption:'-Select-'"></select></td>
                        </tr>
                    </tbody>
                </table>
            </div>           
        </div>
    </form>
</body>
</html>

js file.

function PrimaryUserViewModel() {
    var self = this;

    self.PrimarySiteUsers = ko.observableArray([]);
    self.Users1 = ko.observableArray([]);
    self.Users2 = ko.observableArray([]);

    function addPrimarySiteUser(siteId, siteName, userParam) {
        return {
            SiteId: ko.observable(siteId),
            SiteName: ko.observable(siteName),             
            UserParam: ko.observable(userParam)
        }
    }

    function addUserDropDown(userId, userName, selectedValue) {
        return {            
            UserId: ko.observable(userId),
            UserName: ko.observable(userName),
            SelectedUserId: ko.observable(selectedValue)
        }
    }

    self.Users1().push(new addUserDropDown(1, 'jj', false));
    self.Users1().push(new addUserDropDown(2, 'jk', true));

    self.PrimarySiteUsers.push(new addPrimarySiteUser(1, 'site1', self.Users1()))

    self.Users2().push(new addUserDropDown(1, 'mj', true));
    self.Users2().push(new addUserDropDown(2, 'mk', false));

    self.PrimarySiteUsers.push(new addPrimarySiteUser(1, 'site1', self.Users2()))
}

$(document).ready(function () {
    var primaryUserModel = new PrimaryUserViewModel();
    ko.applyBindings(primaryUserModel);
})

1 个答案:

答案 0 :(得分:0)

您的示例中有许多奇怪的代码,因此我将从基础开始:

您可以通过以下方式在视图模型中设置选择:

  1. 创建要呈现为options的列表,并使用observable存储当前选择

    var vm = {
      choices: [ 1, 2, 3],
      selection: ko.observable(2)
    };
    
  2. 将列表绑定到options以及value框中<select>的可观察对象:

    <select data-bind="options: choices, value: selection"></select>
    
  3. 将值写入selection,该值也位于绑定到options的数组中:

    vm.selection(3); // Selects the last element of the dropdown
    vm.selection(vm.choices[1]) // Select 2
    
  4. 要在代码中使用此功能:

    • 添加value绑定和selection可观察
    • 存储对prim vm的引用,以便我们更新selected属性
    • 循环用户及其UserId以设置新选择

    &#13;
    &#13;
    function PrimaryUserViewModel() {
      var self = this;
    
      self.PrimarySiteUsers = ko.observableArray([]);
      self.Users1 = ko.observableArray([]);
      self.Users2 = ko.observableArray([]);
    
      function addPrimarySiteUser(siteId, siteName, userParam) {
        return {
          SiteId: ko.observable(siteId),
          SiteName: ko.observable(siteName),
          UserParam: ko.observable(userParam),
          selection: ko.observable(null)
        }
      }
    
      function addUserDropDown(userId, userName, selectedValue) {
        return {
          UserId: ko.observable(userId),
          UserName: ko.observable(userName),
          SelectedUserId: ko.observable(selectedValue)
        }
      }
    
      self.Users1().push(new addUserDropDown(1, 'jj', false));
      self.Users1().push(new addUserDropDown(2, 'jk', true));
    
      var primUser1 = new addPrimarySiteUser(1, 'site1', self.Users1());
      self.PrimarySiteUsers.push(primUser1)
      
      // Select jk:
      // 1: find reference to user
      var jkUser = self.Users1()[1];
      // 2: get id (because of `optionsValue: 'UserId'`)
      var jkId = jkUser.UserId();
      // 3: write to selection
      primUser1.selection(jkId);
    
      self.Users2().push(new addUserDropDown(1, 'mj', true));
      self.Users2().push(new addUserDropDown(2, 'mk', false));
    
      self.PrimarySiteUsers.push(new addPrimarySiteUser(1, 'site1', self.Users2()))
    }
    
    var primaryUserModel = new PrimaryUserViewModel();
    ko.applyBindings(primaryUserModel);
    &#13;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    <form id="frmPrimarySiteUser">
      <div class="container">
        <div class="row">
          <span>Setup </span>
        </div>
        <div class="row">
          <table class="table-bordered table-condensed table-hover table-responsive" id="tblEncode">
            <thead>
              <tr>
                <th>Site Name</th>
                <th>User Id</th>
              </tr>
            </thead>
            <tbody data-bind="foreach: PrimarySiteUsers">
              <tr>
                <td><span data-bind="text: SiteName"></span></td>
                <td><select name="ddlUsers" data-bind="options: UserParam, value: selection, optionsText: 'UserName', optionsValue: 'UserId', optionsCaption:'-Select-'"></select></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </form>
    &#13;
    &#13;
    &#13;

    您的代码中发生了许多奇怪的事情,您还应该修复:

    • 不需要时使用new
    • 删除数据绑定为selected,但不执行任何操作
    • 重组一些数据定义和视图模型
    • 对属性使用小写字符&#39;构造函数的第一个字母和大写字母......