AlbatrossCafe
AlbatrossCafe

Reputation: 1842

How to save JSON from an ASP.NET viewmodel into a JavaScript variable?

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.

Upvotes: 3

Views: 1035

Answers (1)

Cacho Santa
Cacho Santa

Reputation: 6914

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

Upvotes: 3

Related Questions