0

i like to pass a string from C# to a javascript variable. The simple way is like:

string aaa = "hello";

and then

<script>
    var javacriptVariable = "<%=aaa%>";
</script>

But, I am asking if there is another way without using a <script> block to to make that variable into a javascript equivalent, direclty using ONLY C# code.

Thank you.

4
  • You could use RegisterClientScriptBlock to write the javascript that sets the variable. Or use json to pull the variable. Commented Oct 8, 2013 at 17:36
  • How do you expect to use the javascript var if it's not inside a script block? Commented Oct 8, 2013 at 17:36
  • RegisterStartupScript msdn.microsoft.com/en-us/library/bahh2fef.aspx Commented Oct 8, 2013 at 17:40
  • You could have a HiddenField in your ASP.NET page and you can set it with C# and access it with javascript. Commented Oct 8, 2013 at 18:36

3 Answers 3

2

Write it to a div's InnerHtml in C#, and get the div's innerHTML from your JavaScript code.

Notes:

  1. You'll have to make the div runat="server".
  2. Notice the difference in the casing (uppercase/lowercase) between the C#'s InnerHtml and js's innerHTML .
Sign up to request clarification or add additional context in comments.

Comments

0

Well, the best method would be to include JSON.NET and output it:

var aaa = <%= JsonConvert.Serialize(aaa) %>;

Then, no matter if it's a string, integer, array, or whatever it'll be serialized in a way that JS can handle it. this will also handle any kind of escaping if necessary (e.g. aaa = "Hello \"World\"!")

Another option is to retrieve it with a handler/AJAX (but that's a little too much overhead for such a simple task).

Finally, you can register the script:

Type type = this.GetType();
string scriptName = "assign aaa";
ClientScriptManager clientScript = Page.ClientScript;
if (!clientScript.IsClientScriptBlockRegistered(type, scripName))
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<script type=\"text/javascript\">")
      .AppendFormat("var aaa = {0};", JsonConvert.Serialize(aaa))
      .Append("</" + "script>");
    clientScript.RegisterClientScriptBlock(type, scripName, sb.ToString());
}

But the above is just a more elaborate way of ending up with a <script> tag anyways.

Comments

0

I actually created a nuget pacakge called Ngon that does exactly this:

http://www.nuget.org/packages/NGon/

It's a rip of the rails gem Gon

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.