Reputation: 1695
I Have 2 View Models for my search function, the first view model contains 2 observable's, the search string and the search type. The second view model is the result based on the search. In my Ajax post I use the Search Type And Search string as variables to obtain the desired result. But I get the following error*Uncaught Error: Unable to parse bindings. Message: ReferenceError: Customers is not defined; Bindings value: foreach: Customers* because the customers array has not been initialized, I apply the bindings for my Second View Model based on search button click. Here is A fiddle To explain better what I am trying to do.
Here is my complete javascript code segment:
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);
});
Upvotes: 1
Views: 759
Reputation: 5147
Well, first of all, you need to be binding each view model to different parts of the page. See Render partial view using knockout.js for how to do that.
Secondly, you need to be initialising an empty search results view model on page load, and binding that to the page section you want, then update that view model once you have results.
As an aside, when your view model has the exact same properties as your data model, I'd use the knockout mapping plugin rather that manually copying the data over.
Upvotes: 1