Output single quotes in Razor generated JavaScript String

Maybe a better solution would be to use JSON serializer, to sanitize your output, which obviously can present a possible injection security risk.

In your particular case, you would write this instead:

var friendArray = @Html.Raw(JsonConvert.SerializeObject(friends.Select(f => f.displayname)));

or if it's more readable to you this way:

    @{
        var arr = JsonConvert.SerializeObject(friends.Select(f => f.displayname));
    }

    var friendArray = @Html.Raw(arr);

arr will be in the form of the JSON array, like ["a","b","c"] and if you join that to your JS line, which creates the friendArray, you'll get something like: var friendArray = ["a","b","c"]; which creates the same array like yours.

Do note that the semicolon (;) at the end of the var friendArray line is necessary to produce the valid JS statement.


You could turn off the encoding of HTML by outputting this way:

@Html.Raw(jsString)