Retrieve Page Instance in a Class

If you are in a case where you need to access the current page from a function inside a class, You don't have to send the page instance into the function parameter, what you can do is to get it using the HttpContext class inside System.Web namespace;

Before starting just add the fully qualified name

using System.Web;

using System.Web.UI;

Below is the code you can use to get the current page.

  public void InjectJavascript()
  {
   Page mypage = (Page)HttpContext.Current.Handler;
   mypage.RegisterStartupScript("alert","<script language=javascript>alert('test')</script>");

  }

Whenever you call this function, it will inject javascript function inside the page you are trying to access.

Of course using the HttpContext.Current, you can access Server, Response, Request, Session etc...

HttpContext.Current.Session

Regards,

HC

 

 

Published 17 May 2007 03:31 AM by haissam

Comments

# JoshStodola said on 18 May, 2007 11:05 AM

You wouldn't want to use this method if your class library needs to be extensible for non-web applications.

# Colin said on 17 September, 2007 04:16 PM

JoshStodola:

When would you be accessing the page class in a non-web appliation?

This site

Search

Go

This Blog

Syndication

Sponsors

  • MaximumASP
  • Social Bookmarking
    Online Shopping
    asp.net hosting
    UK online local dating