将 C# 字符串转换为 JavaScript 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27574853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:39:05  来源:igfitidea点击:

Convert C# string to JavaScript String

javascriptc#asp.netrazor

提问by Sepehr Sobhani

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

有人知道在 Asp.net 中将 C# 字符串转换为 JavaScript 字符串的方法吗?我的代码如下所示:

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


  </script> 



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

回答by Martin Brown

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.JavaScriptStringEncodein 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.Rawlike this:

在写出字符串之前,您需要对字符串进行 JavaScript 编码,否则您的字符串可能包含导致 JavaScript 字符串常量过早终止的字符。您可以使用System.Web 命名空间中的HttpUtility.JavaScriptStringEncode执行此操作。完成后,您需要停止 razor 对 HTML 编码的结果,这可以使用HtmlHelper.Raw完成,如下所示:

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

回答by lante

Try the following:

请尝试以下操作:

var thing = "@(thing)";

回答by John Smith

There are a couple of good ways to do this. But a very clean way is to use a cookie. This is clean because you are not injecting javascript code from the server into your static client code. Writing C# to create JavaScript and then insert that into a variable may have timing issues, depending on when your code runs and what .Net is doing. Be very careful in reading strings back for security concerns.

有几种好方法可以做到这一点。但是一个非常干净的方法是使用 cookie。这是干净的,因为您没有将 javascript 代码从服务器注入到您的静态客户端代码中。编写 C# 来创建 JavaScript,然后将其插入到变量中可能会出现计时问题,具体取决于您的代码何时运行以及 .Net 正在做什么。出于安全考虑,在读取字符串时要非常小心。