Convert C# string to JavaScript String

2019-01-28 11:12发布

问题:

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.