Common objects across a user control

J

Josh Schmidt

I'm building a master page that contains 2 user controls. When any page in
the site loads it will create an object (objUser). The objUser constructer
checks to see if a user cookie exists and if it does will populate a series
of properties including IsLoggedIn. If objUser.IsLoggedIn = False, then the
login user control is displayed. When the user logs (objUser.Login method)
the cookie is created, properties are populated and IsLoggedIn is set to True.

The other user control is a navigation control that will display different
options depending on the type of user. This will check objUser.Type.

Here is my question: How can I create objUser on the master page and
reference it in the code behind for the user controls? Right now I'm
creating the object 3 times, once when the page loads, once when the nav user
control loads, and once when the login control click event fires.

Thanks!
 
B

Brennan Stehling

Josh,

You can create a helpful Property to wrap your access to your user
object. Here is some example code in VB.NET.

Public Shared ReadOnly Property UserObject() As String
Get
If (System.Web.HttpContext.Current.Session("UserObject") Is
Nothing) Then
' create user object and place it into the Session
End If
Return
CStr(System.Web.HttpContext.Current.Session("UserObject"))
End Get
End Property

Basically it holds the value in the session. If it is not already
created it will do so and store it in the Session. I normally place
code like this in a class named Utility and place it in the App_Code
folder. Since it is a shared property (static for C#) you can access
it from any master page, regular page or user control. It will
automatically reference your current user context.

If (Utility.UserObject.IsLoggedIn) Then
' do something
End If

And obviously you would change String to the type of your user object.

Next what you may want to do is add code to your Global.asax to handle
the start and end of a Session with the Session_Start and Session_End
events. You can find information on that here...

http://msdn2.microsoft.com/en-us/library/aa466831.aspx

Look to the bottom for mentions of those events. This page also covers
it.

http://msdn2.microsoft.com/en-us/library/ms973868.aspx

Brennan Stehling
http://brennan.offwhite.net/blog/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,600
Members
45,180
Latest member
CryptoTax Software
Top