简体   繁体   中英

How to pass a string from C# to a javascript variable

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.

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 .

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 (eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM