3

I have the following in my MVC view:

 $(document).ready(ko.applyBindings(new ProfileVm(@Html.Raw(Json.Encode(Model)))));

This is working great, except all of the keys from Model are being encoded with uppercase first letters. How can I invoke the camelCase resolver from the view? Or is there a way to tell Json.Encode to use lowercase resolution?

1

1 Answer 1

11

You should use Newsoft JSON for this:

@{ var json = JsonConvert.SerializeObject(
            Model, 
            Formatting.None, 
            new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
   );

    $(document).ready(ko.applyBindings(new ProfileVm(@Html.Raw(Json.Encode(json)))));
}
Sign up to request clarification or add additional context in comments.

2 Comments

It is good, but isn't completely correct answer. It is better to use new ProfileVm(@Html.Raw(@json))) and put the java script statement outside the razor one.
For me this worked: var json = JSON.parse(@Html.Raw(Json.Encode(JsonConvert.SerializeObject( Model, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }))));

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.