Link to home
Start Free TrialLog in
Avatar of brettr
brettr

asked on

Can SCRIPT defined var be referenced in code behind?

If I define a variable as below, which is global, is there a way to reference it in code behind?

Is this variable global only to the particular page class it is defined in?  If that is the case, why can't it be referenced in code behind as defined below?

Is there any MSDN documentation on this particular scenario?
...
<title></title>
</head>
<SCRIPT Runat="Server">
string MyVar;
</SCRIPT>
<body>
<form id="form1" runat="server">
<div>
 
<% MyVar = " A Test"; %>
...

Open in new window

Avatar of ppittle
ppittle
Flag of United States of America image

Brettr,

What you've run into is more or less by design.  When the asp.net compiler converts your declarative markup into classes that the CLR will work with, it creates two classes per page:  One class for the declarative markup, and one class for the code behind.  The delcarative markup class inherits from the code behind.  This is why if you specify an event handler in your declarative markup, it can't be declared private.  

Because Microsoft expected developers to need to progromatically work with Controls that have been declared declaritively, Visual Studio automatically adds definitions for all of your controls into your code behind class.  In .NET 1.1 this was in the form of a desinger section.  In 2.0 and beyond, it's placed in a seperate file (aspx.designer.cs or aspx.designer.vb). However, this is limited to Controls.  So if you add variables in script elements, they wont be added to your code-behind and you wont be able to access them from your code behind.  For it to work, we'll need to manually add it ourselves.

Once we understand how asp.net is creating classes out of your declartive markup, we can modify your solution above by declaring your variable in the code behind.  Then we can access it from both declarative markup, and code behind:

<html>
<body>
<MyVar="Hello World!!!!"; Response.Write(MyVar); %>

<%-- Code Behind --%>
public partial class MyPage : System.Web.UI.Page
{
protected string MyVar = string.Empty;
}

To see an example of this inheritence in action, change the definition of MyVar in your code-behind to:
private string MyVar = string.Empty;

PJ
Avatar of brettr
brettr

ASKER

What is the inheriting class name in the aspx?  Does Microsoft document how that is derived?  The code behind class usually gets an underscore prepended to its name.  For example, the aspx references:

Inherits="MyNameSpace._MyPage" %>
ASKER CERTIFIED SOLUTION
Avatar of ppittle
ppittle
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial