Passing values between pages

Z

zion

Hello,

In my Aspx.cs page in Page_load event I have for example:
String x;
x = "10";
How can I use the x value in a javascript function in the Aspx page?

thanks
 
S

Smithers

In page_load you can place the value of x into a hidden field. IIRC, you can
add the "runat=server" attribute to a plain 'ole html hidden field. Doing
this makes it accessible to your C# code behind.

-HTH
 
A

Alberto Poblacion

zion said:
In my Aspx.cs page in Page_load event I have for example:
String x;
x = "10";
How can I use the x value in a javascript function in the Aspx page?

One way to do it is to write <%= x %> inside your javascript code in the
aspx page in the place where you want to access x. Note that this will only
work if x is a public field or method inside your class, so it can't be a
local variable of the Page_Load method.

Another way is to build the javascript code inside your server code. You
can then concatenate into the code the value of any variables that you want,
such as the local variable x, and then you send this javascript into the
page by means of any of the methods provided for this purpose, such as
ClientScript.RegisterClientScriptBlock.
 
S

Smithers

To clarify...

Doing this ["runat=server"] makes it [your hidden html field] accessible to
your C# code behind.

In your code behind you'd then write the value of x to the hidden field.

Then the page gets rendered down to the browser where the hidden field has
the value of x.

You can read and write the value of the hidden field via JavaScript in the
client/browser.

Then, on postback, the C# codebehind can read the value of the hidden field
to see what the new value is.

-HTH..

-S
 
A

Alberto Poblacion

Michael S said:
I say x should be a protected field, not public.

Yes, the above shoud read "...will only work with public, protected or
internal fields, properties or methods...".
Since it is advisable to declare variables with a scope that is as
limited as circumstances allow, then you are right, it is best to use
"protected" rather than "public" in this particular case.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top