I am assembling a few lines in JavaScript using Razor. I thought the easiest way would be to assemble the entire JavaScript block first, then output the entire thing. The
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.