English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

where to declare global function & variable?

in global.asax, there's a few sub, application_start and etc

should i declare those functions & var inside app_start sub or outside? after declaring, how to refer back to the var and function? do i need to import something?

2007-02-06 18:10:30 · 2 answers · asked by jchris 3 in Computers & Internet Programming & Design

2 answers

ASP.NET does not work like ASP - you can't really define global functions in the way you're describing. Since .NET is class/assembly based, you should create a class, like Utility or something, and give it static methods that you want to be global, then simply reference that class on every page.

Example:

Namespace MyProject.Global

Public Class Utilities
Public Shared Sub MyMethod(ByVal input As String)
End Sub
End Class

End Namespace

Then in each of your pages, put Imports MyProject.Global

Then wherever you need to use the method, just call Utilties.MyMethod()

2007-02-06 18:25:56 · answer #1 · answered by Rex M 6 · 0 0

You want to write functions that are to be called from within several pages in your application.

The global.asax is not exactly for that purpose. It is used to define global wide application EVENTS. For example, if you want to do some action when the application starts, you write the code under app_start.

What you want however is something different. Add a class to your application and name it something like Utilities. Inside this class, you can define public static functions which you can call from with any page in your application.

public class Utilities
{
public Utilities()
{

}
public static string GlobalFunctionHere()
{
return "Hello World";
}
}


Now from a page you call the function using the following pattern:

Response.Write(
Utilities.GlobalFunctionHere()
);

Thank You!

2007-02-06 19:15:56 · answer #2 · answered by Smutty 6 · 0 1

fedest.com, questions and answers