Output single quotes in Razor generated JavaScript

2019-02-11 17:51发布

问题:

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)