Reputation: 4246
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.
Upvotes: 1
Views: 489
Reputation: 33149
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.
Upvotes: 1
Reputation: 22094
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);
Upvotes: 4
Reputation: 954
Button b = new Button();
b.ID = "btn_test";
b.Text = "test";
b.OnClientClick = "function (s, e) { alert ("+cpt_test+"); }";
Upvotes: 2