0

I have a json variable in the view as follows:

 @{
        string jsontemp = '{"Cars": {"Nissan": [{"Model": "Sentra", "doors": 4},{"Model": "Maxima", "doors": 4}],"Ford": [{"Model": "Taurus", "doors": 4},{"Model": "Escort", "doors": 4}]}}';
}

I want to assign it to a variable in javascript.

<script>
var jsondata = @jsontemp;

var arraydata = JSON.parse(jsondata);

</script>

But I get the following error message:

Uncaught SyntaxError: Unexpected token &

I understand that when the view is run, my json variable is from the format: ["Ford", "BMW", "Fiat"] convert to [&quot;Ford&quot;, &quot;BMW&quot;, &quot;Fiat&quot;]

I want to retrieve the json string from view, and assign it to a variable in the script code, then I parse from that string to the array.

1 Answer 1

2

You need to use @Html.Raw() to output the data in raw form.

Otherwise @ will escape your output by HtmlEncoding it.

<script>
    var jsondata = @Html.Raw(jsontemp);
    var arraydata = JSON.parse(jsondata);

</script>
Sign up to request clarification or add additional context in comments.

Comments

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.