我正在尝试在下拉列表中预选一个值。我正在使用 KnockoutJS 并调用 Web 服务将值推送到我的列表中。但是,我无法预先选择我想要的值。非常感谢您的帮助。我还注意到没有显示放置在 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>