Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 763
Sepehr Sobhani Avatar asked Dec 19 '14 22:12

Sepehr Sobhani


People also ask

How do you convert C to F fast?

Simply multiply the Celsius temperature by 2 and add 30 to it: (Celsius temp. x 2) + 30 = Fahrenheit temp. Here's an example using 30 degrees C.

How do we convert a Celsius?

The formula for converting Fahrenheit to Celsius is C = 5/9(F-32). Fahrenheit and Celsius are the same at -40°. At ordinary temperatures, Fahrenheit is a larger number than Celsius. For example, body temperature is 98.6 °F or 37 °C.

What temperature in Fahrenheit is 50 C?

Answer: 50° Celsius is equal to 122° Fahrenheit.


2 Answers

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))";
like image 168
Martin Brown Avatar answered Sep 22 '22 08:09

Martin Brown


Try the following:

var thing = "@(thing)";
like image 22
lante Avatar answered Sep 22 '22 08:09

lante