Output single quotes in Razor generated JavaScript String

后端 未结 2 381
执念已碎
执念已碎 2021-01-01 12:00

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

2条回答
  •  无人及你
    2021-01-01 12:12

    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.

提交回复
热议问题