我的搜索功能有 2 个视图模型,第一个视图模型包含 2 个可观察对象、搜索字符串和搜索类型。第二个视图模型是基于搜索的结果。在我的 Ajax 帖子中,我使用搜索类型和搜索字符串作为变量来获得所需的结果。但我收到以下错误*未捕获的错误:无法解析绑定。消息:ReferenceError:未定义客户;绑定值:foreach:Customers*因为客户数组尚未初始化,我根据搜索按钮单击为我的第二个视图模型应用绑定。这是一个小提琴来更好地解释我正在尝试做的事情。
这是我完整的 javascript 代码段:
var CustomerSearchViewModel = {
SearchType: ko.observable(""),
SearchString: ko.observable(""),
setSearchType: function (data, element) {
this.SearchType($(element.target).val());
}
}
var CustomerSearhResultViewModelDS = function (data) {
var self = this;
self.CustomerID = ko.observable(data.CustomerID);
alert(self.CustomerID);
self.CustomerName = ko.observable(data.CustomerName);
self.CustomerEMail = ko.observable(data.CustomerEMail);
self.CustomerTelephone = ko.observable(data.CustomerTelephone);
self.CustomerCompanyName = ko.observable(data.CustomerCompanyName);
self.CustomerCompanyAddress1 = ko.observable(data.CustomerCompanyAddress1);
self.CustomerCompanyAddress2 = ko.observable(data.CustomerCompanyAddress2);
self.CustomerCompanyZipCode = ko.observable(data.CustomerCompanyZipCode);
}
var CustomerSearhResultViewModel = function (Customer) {
var self = this;
self.Customers = ko.observableArray(Customer);
$.ajax({
url: "/Services/DataServicesECOM.svc/CustomerSearch",
data: { SearchType: CustomerSearchViewModel.SearchType(), SearchString: CustomerSearchViewModel.SearchString() },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
var MappedCustomer =
$.map(Result.d,
function (item) {
return new CustomerSearhResultViewModelDS(item);
}
);
self.Customers(MappedCustomer);
$('#ModalDetail').modal('show');
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
function ActivateSearch() {
var VM = new CustomerSearhResultViewModel();
ko.applyBindings(VM);
}
$(document).ready(function () {
ko.applyBindings(CustomerSearchViewModel);
});