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.
AntiXSS has JavaScriptEncode, but it's designed for individual items, rather than taking a whole set of, err, settings.
So if you passed in {"UnselectedReason":"None Selected", /.../} it'd eat the quotes and other things, which is probably not what you want. Instead what I'd do is in your ToJson I'd build the settings up with a string builder, something like
StringBuilder sb = new StringBuilder();
sb.Append("{");
foreach(KeyValuePair kv in mySettings)
{
sb.Append("\"");
sb.Append(Microsoft.Security.Application.Encoder.JavaScriptEncode(kv.Key, true);
sb.Append(":");
sb.Append(Microsoft.Security.Application.Encoder.JavaScriptEncode(kv.Value, true);
sb.Append("\",");
}
string outputString = sb.ToString().TrimEnd(",") + "}";
return new HtmlString(outputString);
Note: Code is off the top of my head and hasn't been even typed into VS. It illustrates the principal and may well not compile!