Sepehr Sobhani
Sepehr Sobhani

Reputation: 882

Convert C# string to JavaScript String

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>

Upvotes: 8

Views: 19961

Answers (3)

John Smith
John Smith

Reputation: 601

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.

Upvotes: 0

Martin Brown
Martin Brown

Reputation: 25310

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

Upvotes: 25

lante
lante

Reputation: 7336

Try the following:

var thing = "@(thing)";

Upvotes: 4

Related Questions