Convert C# string to JavaScript String

2019-01-28 10:35发布

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>

3条回答
男人必须洒脱
2楼-- · 2019-01-28 10:54

Try the following:

var thing = "@(thing)";
查看更多
smile是对你的礼貌
3楼-- · 2019-01-28 11:09

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))";
查看更多
淡お忘
4楼-- · 2019-01-28 11:21

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.

查看更多
登录 后发表回答