8

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
  • I think what you're looking for is a way to get a string value from server side (code behind) to client side (javascript). Is that right? Commented Dec 19, 2014 at 22:36
  • The eventAlert(thing) function simply shows the string as an alert, but the code above does nothing unless i manually pass in the string. Commented Dec 19, 2014 at 22:38
  • and this string is held/generated in your c# codebehind? Commented Dec 19, 2014 at 22:39

3 Answers 3

25

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))";
Sign up to request clarification or add additional context in comments.

1 Comment

So this is pretty neat. Depending on your use case it might be more practical to just inject "@myString" however you can use @HttpUtility.JavaScriptStringEncode(value: "hi", addDoubleQuotes: true) and let the method output a string with or without double quotes added to it.
4

Try the following:

var thing = "@(thing)";

2 Comments

This is how you would do it. Sometimes to make sure the razor engine doesn't get confused, it is also useful to use var thing = "@(thing)";.
Works very well until your string has a quote in it.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.