1

I try this time to display variable from my ASP.net code C# in a Javascript function. Here is the C# variable I try to display :

protected static int cpt_test = 0;

This one is an attribute of my class, and the static means I can alterate its value in every each function I have made (don't ask more, it works like this :p).

And finally here is my Javascript code :

Button b = new Button();
b.ID = "btn_test";
b.Text = "test";
b.OnClientClick = "function (s, e) { alert (<%=cpt_test%>); }";

When I compile the code, it gives me an error. I tryied to wrap the <%=cpt_test%> in quotes, but it gives me the string "<%=cpt_test%>" and not "0".

How could I perform translating asp variable in javascript guys ? My final goal is to modify a variable in my asp server code, but for now I try something simple.

Anwar
  • 4,162
  • 4
  • 41
  • 62
  • possible duplicate of [Get variable value from code behind and use in aspx page control](http://stackoverflow.com/questions/8883262/get-variable-value-from-code-behind-and-use-in-aspx-page-control) – Niranjan Singh Oct 14 '14 at 09:05

4 Answers4

4

Your javascript code looks like C# code-behind. Assuming it is that case, you need to correct it to:

Button b = new Button();
b.ID = "btn_test";
b.Text = "test";
b.OnClientClick = string.Format("function (s, e) {{ alert ({0}); }}", cpt_test);
Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
2
Button b = new Button();
b.ID = "btn_test";
b.Text = "test";
b.OnClientClick = "function (s, e) { alert ("+cpt_test+"); }";
Ammaroff
  • 944
  • 7
  • 22
1

You need to actually embed the value in your generated JavaScript, like so:

b.OnClientClick = "function (s, e) { alert ('" + cpt_test + "'); }";

This is because the client-side JavaScript, which will get executed in the browser, has no access to the server-side ASP.NET code or its variables. Hence, if you need an ASP.NET variable value in JavaScript, you have to generate JavaScript that contains that value.

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
-4

make it public

 public static int cpt_test = 0;
Mahmoude Elghandour
  • 2,921
  • 1
  • 22
  • 27