Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pb with variable in my aspx page

Status
Not open for further replies.

beral

Programmer
Jan 7, 2004
12
SE
hello

I have a webform and I am wondering if it possible through my aspx page to have access to a variable that I have defined in my code behind

Many thanks
 
Do you mean that you need your javascript on hte page to have access to the variable?

Because otherwise, when you post back the page, the variable will be available...the only time your webform would need to access it seperate from the code behind is through client script.

Maybe give us more info on what you're trying to do and we can go from there.

D'Arcy
 
yes this is exactly what I would like to do.
I want that my javascript on this page have access to a variable that I have defined in my code behind
 
You can emit client side javascript code to the browser in many different ways.

Arguably the best way to do this is to use the .RegisterStartupScript method of the Page object. For example, let's say that I have a variable, myServerVar in codebehind that I want accessible to a client side javascript function. First, you need to build the client side code that will be sent to the browser:

//this is in your codebehind
int myServerVar = 7;
string script = "<script language=javascript>var myClientVar = " + myVar.ToString() + ";</script>";

Now, you need to invoke the RegisterStartupScript method to send it to the browser:

Page.RegisterStartupScript("clientCode", script);

The net result is that this bit of js code will be emitted to the browser at the bottom of the page... right before the closing </form> tag. As you can see from the javascript, the client side variable, myClientVar, has been declared as a global variable, and as such, will be accessible in any function that you then choose to declare on the page.

If you need to control where on the page the js appears, then you can place an <asp:Label /> on the page, and then just assign the script value to the .Text property of the label. Most times, however, Page.RegisterStartupScript() is more than sufficient.

Good Luck.

-paul

penny.gif
penny.gif

The answer to getting answered -- faq855-2992
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top