5

I'm just trying to get a JSON string from my controller (MVC3 using Razor syntax) into the clients browser...

In My Controller I do this with a simple object (test) that contains an int and a list.

var jasonData = new JavaScriptSerializer().Serialize(test);
ViewBag.JasonData = jasonData;

In the view I do this:

<script type="text/javascript">
    var initialData = @(ViewBag.JasonData);
</script>

Visual Studio shows the data looking fine but when it ends up in the Browser it has the escaping code around all the data which is not good.

&var initialData = {&quot;DateId&quot;:32,&quot;Scores&quo ....

This should be easy! What am I doing wrong??

1
  • jason or json? I hope it's the latter. Commented Oct 21, 2014 at 8:02

1 Answer 1

9

Use @Html.Raw() to prevent the data from being encoded, as follows:

<script type="text/javascript"> 
    var initialData = @Html.Raw(ViewBag.JasonData); 
</script> 
Sign up to request clarification or add additional context in comments.

3 Comments

VS 2012 is giving me a script error (showing as error, not warning) when using this. Razor+Javascript parser bug? The error is on the semicolon, ';'.
@yzorg FYI - if you write the line like var initialData = @(Html.Raw(ViewBag.JsonData)); the Intellisense Error goes away.
This works fine if i have the viewbag.JsonData in the Index method but how should i get the same if it is in some other action result other than Index???

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.