Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get JSON data into a Razor view Script Block

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??

like image 724
Pablo Avatar asked Feb 23 '23 22:02

Pablo


1 Answers

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

<script type="text/javascript"> 
    var initialData = @Html.Raw(ViewBag.JasonData); 
</script> 
like image 126
counsellorben Avatar answered Feb 25 '23 12:02

counsellorben