1

I have this code and it work perfectly:

<script>
   $(function() {
      var modelAsString = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));

      myProject.initialize(ko.mapping.fromJS(modelAsString));
   });
</script>

Note that this script is directly in my view (e.g. MyPage.cshtml)

I'm just wondering why I must use the function fromJS instead of fromJSON.

If I use fromJSON, there is no error but it seems like my viewmodel is not created correctly.

And if possible, it would be greatly appreciated to have an example where I can use fromJSON with the same context; a case where I directly get the Model from the view instead of getting it from an ajax query.

2
  • Why is it a problem that you need to use fromJS? Commented May 29, 2013 at 20:53
  • It's not a problem. I just want to understand why fromJSON don't work in this case and what I must provide if I want to use fromJSON. Commented May 29, 2013 at 21:13

1 Answer 1

2

ko.mapping.fromJSON takes a JSON string then parses it and calls ko.mapping.fromJS internally with the parsed JavaScript object. However if you call ko.mapping.fromJSON with something which is not a string it returns null so no mapping will happen.

So in your case you need to change your modelAsString to hold JavaScript string with wrapping the result of the Html.Raw call with apostrophes then you can use ko.mapping.fromJSON on it:

var modelAsString = '@(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)))';

myProject.initialize(ko.mapping.fromJSON(modelAsString));

Also form the mapping plugin documentation (emphasis added by me):

Working with JSON strings

If your Ajax call returns a JSON string (and does not deserialize it into a JavaScript object), then you can use the function ko.mapping.fromJSON to create and update your view model instead. To unmap, you can use ko.mapping.toJSON.

Apart from the fact that they work with JSON strings instead of JS objects these functions are completely identical to their *JS counterparts.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. This is exactly what I want to know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.