在Dropdown(select)KnockoutJS中预选值

时间:2013-06-26 15:58:00

标签: c# javascript asp.net knockout.js

我正在尝试在Dropdown中预选一个值。我正在使用KnockoutJS并调用webservice将值推送到我的列表中。但是,我无法预先选择我想要的值。非常感谢您的帮助。我也注意到没有显示ko.utils.arrayFirst中的警报。谢谢!

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="~/platform/vendors.asmx" />
        <asp:ServiceReference Path="~/platform/checkBooks.asmx" />
    </Services>
</asp:ScriptManager>
</form>
<div>
    <p>
        Checkbooks:
        <select data-bind="options: cb, value: choice, optionsText: 'name'"></select>

    </p>
</div>

<script type="text/javascript">
    function errorHandler(errorObject) {
        var errType = errorObject._exceptionType;
        var errMsg = errorObject._message;
        window.alert("ERROR" + errType + ":" + errMsg);
        return false;
    }

    ko.observableArray.fn.find = function (prop, data) {
        var valueToMatch = data[prop];
        return ko.utils.arrayFirst(this(), function (item) {
            return (item[prop] === valueToMatch);
        });
    };

    function viewModel() {
        var self = this;
        self.cb = new ko.observableArray([]);

        self.call = function () {
            try {
                checkBooks.list("accounting", 2, "name:", self.retCheckBooks, errorHandler);
            }
            catch (ex) {
                alert(ex.message);
            }
        }
        self.retCheckBooks = function (results) {
            for (var i = 1; i <= results.length; i++) {
                self.cb.push({ id: i, name: results[i].shortName });
            }
        }
        var choice = { id: 4, name: "VCSTPAY" };
        self.choice = ko.observable(self.cb.find("id", choice));
    }
</script>

<script type="text/javascript">
    $(document).ready(function () {
        vm = new viewModel();
        vm.call();
        ko.applyBindings(vm);
    });

</script>

1 个答案:

答案 0 :(得分:1)

optionsValue: "id"添加到数据绑定中,并将选项更改为:

self.choice = ko.observable(choice.id);

默认情况下,KO不知道如何比较您的选择对象以匹配value之一options