I would use the following:
<script type="text/javascript"> var initialData = @Html.Raw(new JavaScriptSerializer().Serialize(Model)); </script>
This is exactly the same as your example (pay attention to Html.Raw ).
If you want the result (html) to be encoded, or your code returns IHtmlString:
<script type="text/javascript"> var initialData = @(new JavaScriptSerializer().Serialize(Model)); </script>
You want to use the @( ... ) syntax because using @new JavaScriptSerializer(..) will let the Razor parser stop in the first space (after the new one).
Syntax:
<script type="text/javascript"> var initialData = @{ new JavaScriptSerializer().Serialize(Model); }; @* <== wrong *@ </script>
does not work because it is called by new JavaScriptSerializer , but discards the output.
source share