Let's say I have following ASP.NET Web Form engine code, how can I express it in Razor engine?
<script type="text/javascript">
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
</script>
Thanks Hardy
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 (note the Html.Raw
).
If you want the output (html)encoded or your code returns an IHtmlString :
<script type="text/javascript">
var initialData = @(new JavaScriptSerializer().Serialize(Model));
</script>
You do want to use @( ... )
syntax, because using @new JavaScriptSerializer(..)
will let the Razor parser stop at the first space (after new).
The syntax like this:
<script type="text/javascript">
var initialData = @{ new JavaScriptSerializer().Serialize(Model); }; @* <== wrong *@
</script>
does not work because it will call new JavaScriptSerializer
, but discard the output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With