Friday, April 29, 2011

ASP.NET - How do you reference a class that is not in app_code

I have created a MasterPage called MyMasterPage.

public partial class MyMasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

I have also created a class called Class1 in app_code:

public class Class1
{
    public Class1()
    {
      MyMasterPage m;
    }
}

In Class1 I would like to reference MyMasterPage but I get a compiler warning:

The type or namespace name 'MyMasterPage' could not be found (are you missing a using directive or an assembly reference?)

What code do I need to add to get this to work?

The classes are in folders as follows:

alt text

From stackoverflow
  • Try putting your master page in a namespace

    Petras : That doesn't work, then it doesn't recognize the namespace
  • You won't be able to reference MyMasterPage unless you put it under App_Code as well. Normally in such a situation you would create a base master page that inherits from MasterPage. e.g.

    public partial class MasterPageBase : System.Web.UI.MasterPage
    {
       // Declare the methods you want to call in Class1 as virtual
       public virtual void DoSomething() { }
    
    }
    

    Then in your actual master pages, instead of inheriting from System.Web.UI.MasterPage,inherit from your MasterPageBase. Overwrite the virtual methods in your inheriting pages.

    public partial class MyMasterPage : MasterPageBase
    

    In Class1 where you need to refer to it (and I'm assuming you get the master page from a Page class' MasterPage property, your code will look like...

    public class Class1
    {
        public Class1(Page Target)
        {
          MasterPageBase _m = (MasterPageBase)Target.MasterPage;
          // And I can call my overwritten methods
          _m.DoSomething();
        }
    }
    

    It's quite a long winded way but so far the only thing that I can think of that works given the ASP.NET model.

  • fung has a nice suggestion by using a Base page. The App_Code files are stored in a different assembly then the aspx pages. This occurs with Website Projects.

    I'm not sure if you have the option in your case. But if you choose the Web Application Project instead of a Website Project, then you won't have this problem.

    Here is a blog post that may shed some light: VS 2005 Web Project System: What is it and why did we do it? by Scott Guthrie

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.