Reputation: 9660
How do I access a page class from another class. For example I have:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
}
Why can I not access it from another class in App_Code folder?
public class MyClass
{
public MyClass() {}
public void DoSomething(object o)
{
// The following line won't compile.
MyPage page = o as MyPage;
}
}
I just figured it out (thanks to Fujiy) that for some reason this is the case with website project, but is not a problem with web application project in VS. If anyone has any clues as to why, please share your thoughts. Thank you :)
Upvotes: 0
Views: 2911
Reputation: 75814
I see nothing wrong with your code as posted, most likely you've got a namespace problem.
edit: gah, just noticed that you mentioned this was a website project. It's been a while since I deigned to start one of those :) but I believe this stems from the fact that App_Code is run-time compiled. It would take a better man than me to explain why that creates the problem, but long story short I'd just avoid website projects in general.
Upvotes: 4
Reputation: 1665
You can do this, afaik:
System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
Be careful where you call that though, because obviously at different points in your code the page won't be available. For example, Application_Start in global.asax.
Upvotes: 2