forum

Home / DeveloperSection / Forums / bind knockoutjs with mvc view is not work

bind knockoutjs with mvc view is not work

Mark M231110-Nov-2014

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


Updated on 10-Nov-2014

Can you answer this question?


Answer

1 Answers

Liked By