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.

1

4 Answers 4

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

Comments

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

Comments

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.

Comments

-4

make it public

 public static int cpt_test = 0;

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.