Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output single quotes in Razor generated JavaScript String

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;; 
like image 761
Dave Avatar asked Feb 06 '13 14:02

Dave


People also ask

How to use single quote in JavaScript string?

Enclosing Quotation Marks That means strings containing single quotes need to use double quotes and strings containing double quotes need to use single quotes. "It's six o'clock."; 'Remember to say "please" and "thank you."'; Alternatively, you can use a backslash \ to escape the quotation marks.

How to use double quotation marks in JavaScript?

to show double quote you can simple use escape character("\") to show it.

Can you use Razor syntax in JavaScript?

You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser. It's meant to be executed server-side.

What languages does Razor consist of?

Razor is an ASP.NET programming syntax used to create dynamic web pages with the C# or VB.NET programming languages. Razor was in development in June 2010 and was released for Microsoft Visual Studio 2010 in January 2011. Razor is a simple-syntax view engine and was released as part of MVC 3 and the WebMatrix tool set.


1 Answers

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

@Html.Raw(jsString) 
like image 163
Arjan Einbu Avatar answered Sep 20 '22 02:09

Arjan Einbu