Reputation: 71
How to declare a global variable or a public sub in a web application that all aspx pages can have access to?
Upvotes: 2
Views: 15557
Reputation: 63
Global.asax inherits from YourWebSiteApplicationClass...
public class YourWebSiteApplicationClass : HttpApplication
{
public string GlobalVariable;
public YourWebSiteApplicationClass()
{
GlobalVariable = "GLOBAL_VARIABLE";
}
}
...and in any .aspx or .cs(.vb) file...
<% = ((YourWebSiteApplicationClass)this.ApplicationInstance).GlobalVariable %>
Return "GLOBAL_VARIABLE".
Upvotes: 0
Reputation: 2467
1.You can use session variables which will be available to all pages in the scope of current session.
C#
Session("name")=value;
2.You can use application variables which will be available to entire application code untill application ends.
Application("name") = value;
Upvotes: 0
Reputation: 34810
"Global" variables can be kept in Cache using Cache.Add
, or Application state using Application.Add
.
"Globally-available" methods are generally an antipattern and should be avoided. If you need a utility function you can add a static method to a class, but beware the Ball of Mud antipattern.
Upvotes: 1