问题
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 problem is, the single quotes are being rendered as & #39;.
Is it possible to change the last line to get this to write correctly:
var friendArray = new Array();
@{
int i = 0;
string jsString="";
foreach(var friend in friends)
{
jsString = jsString + "friendArray[";
jsString = jsString + i.ToString();
jsString = jsString + "]='";
jsString = jsString + friend.displayname;
jsString = jsString + "';";
i++;
}
@jsString;
}
The above generates this:
friendArray[0]=& #39;Hollister& #39;;friendArray[1]=& #39;Festus& #39;;
回答1:
You could turn off the encoding of HTML by outputting this way:
@Html.Raw(jsString)
回答2:
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.
来源:https://stackoverflow.com/questions/14731421/output-single-quotes-in-razor-generated-javascript-string