How do I properly encode JavaScript in the following context:
<html>
...
<script type="text/javascript">
var settings = @Html.PleaseEncode(settings.ToJson());
// ...
</script>
</html>
The values in my JSON objects are set by the application administrator, so I assume they need properly encoded -- both for HTML and JavaScript.
I'm using System.Web.Script.Serialization.JavaScriptSerializer to do the JSON encoding.
It looks like JavaScriptSerializer does some encoding as it outputs the text <None>
as \u003cNone\u003c
, but I'm not sure how safe it is. Right now, I'm using @Html.Raw
as it works given safe input. It generates the following:
var settings = {"UnselectedReason":"None Selected", /*...*/};
If I use @Html.Encode
I then get:
var settings = {&quot;UnselectedReason&quot;:&quot;None Selected&quot;, /*...*/};
I've tried with and without AntiXSS but I see no difference either way.