Convert C# string to JavaScript String

女生的网名这么多〃 提交于 2019-12-18 08:47:14

问题


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>

回答1:


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))";



回答2:


Try the following:

var thing = "@(thing)";



回答3:


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.



来源:https://stackoverflow.com/questions/27574853/convert-c-sharp-string-to-javascript-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!