Equivalent Razor Syntax of Following Statement?
Let's say I have following ASP.NET Web Form engine code, how can I ex开发者_运维问答press 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.
精彩评论