Search code examples
jqueryasp.net-mvcknockout.jsknockout-mapping-pluginknockout-3.0

knockout mapper doesn't work properly


I went through lot of knockout articles but I'm failing to mapped below json object to knockout view model

{
   "VehicleModels":[
      {
         "Name":"Model 1",
         "Model":{
            "MakeName":"Ford"
         },
         "Styles":[
            {
               "StockImage":"http://google.com"
            }
         ]
      },
      {
         "Name":"Model 2",
         "Model":{
            "MakeName":"Ford"
         },
         "Styles":[
            {
               "StockImage":"http://bing.com"
            }
         ]
      }
   ]
}

this is my jsfiddle code jsfiddle Link


Solution

  • Ok I've updated the fiddle:

    Essentially:

    var mapping = {
        'Styles': {
            create: function (options) { // I fiddled with this, play around with it
                var self = options.data;
                    self.stockimage = ko.observable();
                    return self;
            }
        }
    };
    
    var data = {"VehicleModels":[{"Name":"Model 1","Model":{"MakeName":"Ford"},"Styles":[{"StockImage":"http://google.com"}]},{"Name":"Model 2","Model":{"MakeName":"Ford"},"Styles":[{"StockImage":"http://bing.com"}]}]};
    
    var viewModel = ko.mapping.fromJS(data,mapping); // Here you did not need to put this as the 3rd parameter
    
    ko.applyBindings(viewModel); // you need to apply the bindings at some point
    

    And finally, you've tried to specify a value to a span:

    <span data-bind='value: Name' />
    

    Spans don't have values I think you wanted text:

    <span data-bind='text: Name' />