0

In C#, I pass an object from my API call to the UI, and want to then automatically map the properties of that object, to a view model. I'm hoping to do this with the mapping plugin for Knockout.

 public class MyModel
    {
        public int ID { get; set; }

        [Display(Name ="Debt Name")]
        [Required(ErrorMessage = "A description is required")]
        public string Description { get; set; }

    }

That's a simplified version of the model I pass to the UI from my API call (WebAPI).

In Javascript, I have defined a class that I want to populate:

class Model {
    id: KnockoutObservable<number>;
    description: KnockoutObservable<string>;
}

That's outside of my ViewModel.

In my view model, I create the model objects, and in my constructor, try to populate the class using mapping. You can see my commented out manual version which works, but I'm trying to go away from that:

class DebtViewModel {

    model: Model = new Model();

    constructor() {

        //this.model.id = ko.observable(0);
        //this.model.description = ko.observable("");

        $.get("/api/debt/1")
            .done((data) => {

                this.model = ko.mapping.fromJSON(data);

                //this.model.id(data.ID);
                //this.model.description(data.Description);
    }); 

However, mapping doesn't seem to work. I don't get an error, but the model just seems to be an empty function.

Can this be done? What am I doing wrong?

Craig
  • 18,074
  • 38
  • 147
  • 248

2 Answers2

0

Serialize your view model into JSON using @Html.Raw(JsonConvert.SerializeObject(this.Model))

for example from this answer

$(function () {
    var jsonModel = '@Html.Raw(JsonConvert.SerializeObject(this.Model))';
    var mvcModel = ko.mapping.fromJSON(jsonModel);

    var myViewModel = new viewModel();
    var g = ko.mapping.fromJS(myViewModel, mvcModel);

    ko.applyBindings(g);
});
Community
  • 1
  • 1
Svek
  • 12,350
  • 6
  • 38
  • 69
0

I believe you will have to switch from .fromJSON to .fromJS and use the three parameter method of the knockout mapping api:

ko.mapping.fromJS(data, {}, this.model);
travis.js
  • 5,193
  • 1
  • 24
  • 21