Saturday, March 31, 2012

Where do global variables go in ASP dot net?

I have just started in ASP.NET. I did ASP years ago but have
forgotten most of it.

As I remember in the old ASP, you put global variable in the
global.asa file. But my question is on ASP.NET. I would think global
variables would go in global.asax, but that doesn't seem to work.

Let me make sure I am even using the correct termonology. I just have
one web form, but it resets the variables every time it is reloaded,
and I want a place to store variables that I do not want reset when
the form is reloaded. I think of those as global variables, but maybe
that is the wrong term.

Hello tomcarr,

asp.net is OO language based, so you could declare a public static member for the Global class as an equivalent to the global vars approach. Here is a sample:

' Global.asax.vb
Public Class Global
Inherits System.Web.HttpApplication

Public Shared MyGlobalInteger As Integer = -1

' ...
End Class

' Any page
Dim MyInt As Integer = Global.MyGlobalInteger

Anyway i'd suggest you look into documentation for the various asp.net options for storing state, like the Application (application scope), Session (session scope), and ViewState (page scope) objects.

Regards. -LV


Thanks for you help LV.

I am reading about application state and session state as yousuggested. One thing I am not clear on. I can create asession state variable in code just by doing:

Session("Message") = "MyMsg"

But is there some way I can define the variable as a string or integer or whatever doing it this way?

.

> I can create a session state variable in code just by doing: Session("Message") = "MyMsg"
> But is there some way I can define the variable as a string or integer or whatever doing it this way?

I'm afraid not. The Session store (as Application and ViewState) holds generic objects. So you can assign to it whatever object reference or value type (the latter gets "boxed"...), and just remember to cast to the proper type when retrieveing the value (anyway the compiler throws an error if you don't cast and have option stric on).

In instance:

Session("MyInteger") = -1
Session("MyString") = "Test"
Session("MyObject") = New MyCustObject()

Dim MyInt As Integer = CInt(Session("MyInteger"))
Dim MyStr As String = CStr(Session("MyString"))
Dim MyObj As MyCustObject = CType(Session("MyObject"), MyCustObject)

Regards. -LV

0 comments:

Post a Comment