Equivalent razor syntax for the following statement?

Say I have an ASP.NET Web Form engine code, how can I express it in the Razor engine?

<script type="text/javascript"> var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>; </script> 

Thanks Hardy

+6
source share
1 answer

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.

+5
source

Source: https://habr.com/ru/post/896130/


All Articles