转换C#字符串的JavaScript字符串 [英] Convert C# string to JavaScript String
问题描述
有谁知道一种方法来一个C#字符串转换为JavaScript字符串是Asp.net。我的code是这样的:
<脚本>
@ {串的事情=猫;}
VAR的事情=字符串(@thing);
< / SCRIPT>< / DIV>
<身体的onload =eventAlert(事)>< /身体GT;
您需要的JavaScript恩code您的字符串你写出来之前,否则你的字符串可能含有引起的JavaScript字符串常量字符将被终止prematurely。您可以在系统的 HttpUtility.JavaScriptStringEn code 做到这一点名.web命名空间。一旦你这样做,你需要从HTML停止剃刀编码,这可以用的 HtmlHelper.Raw 是这样的:
@ {串的事情=猫特殊字符\\'£$%^&安培;!*()@ ;:;}
VAR的事情=@ Html.Raw(HttpUtility.JavaScriptStringEn code(事));
Does anybody know a way to convert a C# string to a JavaScript String is Asp.net. My code looks like this:
<script>
@{string thing = "Cats";}
var thing = String(@thing);
</script>
</div>
<body onload="eventAlert(thing)"></body>
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))";
这篇关于转换C#字符串的JavaScript字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!