Ketone Cops

July 7, 2008

Referencing page from Class file in App_Code

Filed under: ASP.NET 2.0,programming — delroger @ 1:02 pm

If you need to reference the Page control from a Class file (for instance, for adding a ClientScript) without passing the Page instance as a parameter to a Function or Sub, you can use the following: 

Dim pg As Page = HttpContext.Current.Handler 

You can then use this instance just as you would in the code-behind of the page itself.

For instance, I use this code to create Javascript alerts on my webpages:

Public Shared Sub CreateMessageAlert(ByRef clientScript As System.Web.UI.ClientScriptManager, ByVal strMessage As String, ByVal strKey As String)
 Dim context As HttpContext = HttpContext.Current
 Dim strScript As String = “”
 If (Not clientScript.IsStartupScriptRegistered(strKey)) Then
clientScript.RegisterStartupScript(context.GetType(), strKey, strScript)
 End If
End Sub

(This code was based on some found elsewhere – apologies for not referencing exactly where, since there are a few examples floating around and I don’t remember where I first saw it!)

From a Class file in the App_Code folder, this could then be called like so:

Dim newGuid As Guid = Guid.NewGuid()
Dim pg As Page = HttpContext.Current.Handler
CreateMessageAlert(pg.ClientScript, “Your message here”, newGuid.ToString())

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: