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.

AlbatrossCafe
  • 1,710
  • 6
  • 26
  • 49

1 Answers1

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

AlbatrossCafe
  • 1,710
  • 6
  • 26
  • 49
Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
  • I just tried it. I'm sure `@Html.Raw()` and `JSON.parse()` are part of the answer. This converts the `"` 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 Sep 16 '15 at 00:14
  • 1
    @AlbatrossCafe there should be no quotes around JSON... because you know it is JSON already. (there are more approaches with correct implementation http://stackoverflow.com/questions/4072762/how-do-i-write-unencoded-json-to-my-view-using-razor ) – Alexei Levenkov Sep 16 '15 at 00:21
  • 1
    @AlbatrossCafe thanks for the edit. Glad I could try to help. – Cacho Santa Sep 16 '15 at 00:56
  • 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 Sep 16 '15 at 02:23
  • @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 – AlbatrossCafe Sep 16 '15 at 16:58
  • i have two questions. what Json.Encode does and what Html.Raw does ? – Monojit Sarkar May 18 '17 at 09:55