Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent Razor Syntax of Following Statement?

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

like image 931
hardywang Avatar asked Aug 29 '11 14:08

hardywang


1 Answers

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.

like image 87
GvS Avatar answered Oct 13 '22 03:10

GvS