Friday, July 06, 2007

Global Variables in ASP.Net

If you need to carry a variable from one page to another, you have a few options with asp.net. The method best suited for you depends on the way the data will be used. The first option is to use session variables. Session variables allow you to keep the information hidden from the user by storing the data in server memory or in an SQL Database (see web.config). To store the value type:
Session("FirstName") = "Todd"
And to retrieve the value, type:
Dim firstname As String = CStr(Session("firstName"))
This variable will be available to you as long as a user's session exists. When their session expires, asp.net will release the data from memory.

You can also accomplish the same task by carrying the value in the URL. This is generally not recommended for user information as it can be seen by the user and easily hacked. However it is recommended in cases where you want a user to be able to link to a specific instance of your asp.net page (i.e. having an articleID on a generic page to display articles).
Dim articleid As Integer = CInt(Request.QueryString("articleid"))
If you only need to retain a variable when posting a page back to itself, you should use the viewstate. It works similarly to a hidden input field in html by placing the value in html code that is not displayed. However, items in the viewstate are encoded so that they cannot be easily deciphered by users. Syntax is similar to sessions, to place in viewstate:
viewstate("FirstName") = "Todd"
To get from viewstate:
Dim fname As String = CStr(viewstate("FirstName"))
If you would like to have a global variable that is static, for example, an sql connection string, I recommend creating a class, and creating the value as a public property of that class. This way you can return your values as a specific data type to enforce better programming.
Public Class Globals
Public ReadOnly Property connstring() As String
Get
Return "server=WebSqlServer; database=Authors; uid=sa; pwd=abcdefg;"
End Get
End Property
End Class
If you need a dynamic variable that spans across individual user sessions (ie keeping a count of active users on your site), you must store the variable in the application object.
Application("usercount") = CInt(Application("usercount")) + 1


Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us.

0 Comments: