Sunday, May 19, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  151] [ 7]  / answers: 1 / hits: 18104  / 10 Years ago, fri, december 19, 2014, 12:00:00

Does anybody know a way to convert a C# string to a JavaScript String in Asp.net. My code looks like this:



<script>
@{string thing = Cats;}
var thing = String(@thing);


</script>



</div>
<body onload=eventAlert(thing)></body>

More From » c#

 Answers
7

You need to JavaScript Encode your string before you write it out, otherwise your string may contain characters that cause the JavaScript string constant to be terminated prematurely. You can do this with HttpUtility.JavaScriptStringEncode in the System.Web namespace. Once you have done that you need to stop razor from HTML Encoding the result which can be done with HtmlHelper.Raw like this:



@{string thing = Cats Special Chars !'£$%^&*()@;:;}
var thing = @Html.Raw(HttpUtility.JavaScriptStringEncode(thing));

[#68430] Wednesday, December 17, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;