Hi Guys
I am new in knockoutjs, i am trying to bind the view, but cannot. Data from server is fetching fine, ajax is working fine, but not binding issue.
Here is my js code:
var UserViewModel = function () {
var self = this;
//Declare observable which will be bind with UI
self.Id = ko.observable("0");
self.FirstName = ko.observable("");
self.LastName = ko.observable("");
//The Object which stored data entered in the observables
var UserData = {
Id: self.Id || 0,
FirstName: self.FirstName || '',
LastName: self.LastName || ''
};
//Declare an ObservableArray for Storing the JSON Response
self.Users = ko.observableArray([]);
GetUser(12); //This is server side method.
function GetUser(userId) {
//Ajax Call Get All Employee Records
$.ajax({
type: "GET",
url: "/api/Users/" + userId,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert("success");
UserData = response.data.UserData;
alert(UserData.FirstName); //This is showing me correct name.
self.Users(response.data.UserData); //Put the response in ObservableArray
},
error: function (error) {
alert(error.status);
}
});
//Ends Here
}
}
ko.applyBindings(new UserViewModel());
Here is my view:
<form class="form-horizontal" data-bind="with: UserData">
<div class="row">
<div class="control-group">
<label class="control-label">First Name</label>
<label class="control-label" data-bind="text: FirstName"></label>
</div>
</div>
<div class="row">
<div class="control-group">
<label class="control-label">Last Name</label>
<input type="text" placeholder="Last Name" data-bind="value: LastName">
</div>
</div>
Thanks
Anonymous User
10-Nov-2014Your problem is that you are trying to two-way data-bind against a non-observable property, so when you update it it isn't notifying the UI. Make your user an observable and set it to an instance of an object or create a model to derive your properties from.