3

I have a page that loads a viewmodel. In the viewmodel is a single property that contains a blob of JSON:

public string PageJson { get; set; }

In the view, I want to store it into a JavaScript variable, so I render it as:

<script>
    var _pageJson= JSON.parse('@Html.Raw(Model.PageJson)');
</script>

The problem I'm having is that this JSON blob spans multiple lines, so when I try to assign it to a variable, it is giving me an error as if I tried to assign a JavaScript variable like this:

var _pageJson = '{
  "PageCategories": [
    {
      "CategoryID": 4405958680,
      "Description": "Advertising & Promotions"
    },
//........code continues.........//

This of course results in an error after the first bracket since a string can't span multiple lines without either an ending quote and the + symbol or the \ symbol. How can I get JavaScript to properly populate this variable? All I can think of is adding a \ after each line of the JSON in the controller but that seems absolutely ridiculous.

1 Answer 1

3

I think this worked for me in the past, I don't have a Windows PC here to test it though.

You will need to encode the JSON value before:

var yourModel = JSON.parse(@Html.Raw(Json.Encode(Model.PageJson)));

No need to have quotes, thanks: @AlexeiLevenkov

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

6 Comments

I just tried it. I'm sure @Html.Raw() and JSON.parse() are part of the answer. This converts the &quot; escaped characters into actual " characters, which is good. However, it still parses out the JSON across multiple lines so I receive the same error.
@AlbatrossCafe there should be no quotes around JSON... because you know it is JSON already. (there are more approaches with correct implementation stackoverflow.com/questions/4072762/… )
@AlbatrossCafe thanks for the edit. Glad I could try to help.
If Model.PageJson is already JSON, there's no need for JSON.parse at all. Just simply do var yourModel = @Html.Raw(Json.Encode(Model.PageJson));
@Rob that was his original answer before my edit. @Html.Raw(Json.Encode(Model.PageJson)) seems to return a string such as: {\r\n \"MarketplaceCategories\": [\r\n {\r\n \"CategoryID\": 4405958689,.......... So, in order to remove all the newline & escape characters I had to use JSON .parse() and now it is a normal, accessible JS object
|

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.