Search code examples
asp.net-mvcknockout-mapping-plugin

Knockout mapping not working for JSON object


function Employee() {
 return @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)) 
};

function EmployeeList(Employee) {
 var map = ko.mapping.fromJS(Employee); return map; 
}

$(document).ready(function () {
 var obj = { emp: ko.observable(new EmployeeList(new Employee)) }; 
ko.applyBindings(obj); 
});

Solution

  • You should use an observableArray, which the ko mapping plugin is already creating for you, and map in an actual array of objects, see this fiddle :

    function Employee() {
        return  [{Name:"test", Address:"test"}] ;
    };
    
    function EmployeeList(Employee) {
     var map = ko.mapping.fromJS(Employee); 
        return map(); 
    }
    
    $(document).ready(function () {
     var obj = { emp: EmployeeList(Employee) }; 
    ko.applyBindings(obj);
    });
    

    Note how I changed your EmployeeList function to return map() and not map - map is a function, you want to return the actual values wrapped by that function - this allows you to specify obj much more cleanly - no need to wrap map in yet another observableArray...

    Hope that helps...