Thought to drop a line of code or two based on Torbjörn Hansson's golden answer:
public static class U
{
private static readonly GeneralPurposeJsonJavaScriptEncodeConverter _generalEncoder = new GeneralPurposeJsonJavaScriptEncodeConverter();
static public IHtmlString Js(this object obj) => new HtmlString(JsonConvert.SerializeObject(obj, _generalEncoder));
private sealed class GeneralPurposeJsonJavaScriptEncodeConverter : JsonConverter //0
{
private static readonly Type TypeOfString = typeof(string);
public override bool CanConvert(Type objectType) => objectType == TypeOfString;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => reader.Value;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => writer.WriteRawValue(Microsoft.Security.Application.Encoder.JavaScriptEncode((string) value, emitQuotes: true)); //1
}
//0 https://stackoverflow.com/a/28111588/863651 used when we need to burn raw json data directly inside a script element of our html like when we do when we use razor
//1 note that the javascript encoder will leave nonenglish characters as they are and rightfully so apparently the industry considers text in html attributes and inside
// html text blocks to be a battery for potential xss exploits and this is why the antixsslib applies html encoding on nonenglish characters there but not here one
// could make the claim that using unicode escape sequences here for nonenglish characters could be potentionally useful if the clients receiving the server html response
// do not support utf8 however in our time and age clients that dont support utf8 are rarer than hens teeth so theres no point going this direction either
}
And here are some examples on how to use it (and when not to use it):
<span>
@someStringWhichMightContainQuotes @* no need to use .Js() here *@
</span>
@* no need to use .Js() here *@
<input value="@someStringWhichMightContainQuotes" />
@* no need to use .Js() here either - this will work as intended automagically *@
@* notice however that we have to wrap the string in single-quotes *@
<button onclick="Foobar( '@("abc \" ' ")' )"> Text </button>
@* The resulting markup will be:
<button onclick="Foobar( 'abc " ' ' )"> Text </button>
Which will work as intended *@
And last but not least:
<script type="text/javascript">
someJsController.Init({
@* containerSelector: “#@(containerId.Js())”, ← wrong dont do this *@
containerSelector: “#” + @(containerId.Js()), @* ← correct *@
containerSelector2: @($"#{container2Id}".Js()), @* ← even better do this for readability *@
simpleString: @(Model.FilterCode.Js()), @* all these will serialize correctly *@
someArray: @(Model.ColumnsNames.Js()), @* by simply calling the .js() method *@
someNumeric: @(Model.SelectedId.Js()),
complexCsharpObject: @(Model.complexCsharpObject.Js())
});
</script>
Hope this helps.