Reputation: 2364
This is a weird one.
Here is my view:
<table class="SelectedPerson">
<tr><td>Emp ID</td><td><input data-bind="value : EmpID, event : { keypress : loadJson }" type="text" /></td></tr>
<tr><td>Net ID</td><td><input data-bind="value : NetID, event : { keypress : loadJson }" type="text" /></td></tr>
<tr><td>First Name</td><td><input data-bind="value : FirstName, event : { keypress : loadJson }" type="text" /></td></tr>
</table>
and my results
<table>
<thead>
<tr>
<td>EmployeeID</td>
<td>NetID</td>
<td>FirstName</td>
<td>LastName</td>
</tr>
</thead>
<tbody id="PersonListViewModel" data-bind="foreach : people">
<tr>
<td data-bind="text : EmpID"></td>
<td data-bind="text : NetID"></td>
<td data-bind="text : FirstName"></td>
<td data-bind="text : LastName"></td>
</tr>
</tbody>
</table>
my ViewModel
var ViewModel = function (EmpID, NetID, FirstName) {
var self = this;
self.EmpID = ko.observable(EmpID);
self.NetID = ko.observable(NetID);
self.FirstName = ko.observable(FirstName);
self.people = ko.observableArray([]);
self.loadJson = function (data, event) {
var objectify = ko.toJS(self);
console.log(objectify.EmpID);
if (event.which == 13) {
var objectify = ko.toJS(self);
console.log(objectify.EmpID);
console.log(ko.toJSON(self));
$.ajax({
dataType: "json",
url: '/Home/GetRecords',
data: {
"json": ko.toJSON(data)
},
success: function (data) {
self.people(data);
console.log(data);
},
error: function () {
alert("error");
}
});
}
return true;
};
};
var vm = new ViewModel();
ko.applyBindings(vm);
It talks to a C# method which accepts the JSON in as a parameter and returns the results based on what you enter. That bit works fine in isolation.
However here is what happens: Imagine this database
[
{"EmpID":"123", "FirstName":"Jim"},
{"EmpID":"124", "FirstName":"Bob"}
]
Any ideas?
Upvotes: 0
Views: 50
Reputation: 4363
You should be using the keyup
event. The reason that you are one key behind is that the model hasn't updated.
<table class="SelectedPerson">
<tr>
<td>Emp ID</td>
<td>
<input data-bind="value : EmpID, event : { keyup : loadJson }" type="text" />
</td>
</tr>
<tr>
<td>Net ID</td>
<td>
<input data-bind="value : NetID, event : { keyup : loadJson }" type="text" />
</td>
</tr>
<tr>
<td>First Name</td>
<td>
<input data-bind="value : FirstName, event : { keyup : loadJson }" type="text" />
</td>
</tr>
</table>
Working example: https://jsfiddle.net/w7c596L0/
Upvotes: 1