3

我创建了一个名为 MyMasterPage 的 MasterPage。

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

    }
}

我还在 app_code 中创建了一个名为 Class1 的类:

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

在 Class1 中,我想引用 MyMasterPage 但我收到编译器警告:

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

我需要添加什么代码才能使其正常工作?

这些类位于文件夹中,如下所示:

替代文字 http://www.yart.com.au/stackoverflow/masterclass.png

4

3 回答 3

5

除非您也将它放在 App_Code 下,否则您将无法引用 MyMasterPage。通常在这种情况下,您将创建一个从 MasterPage 继承的基本母版页。例如

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

}

然后在您的实际母版页中,而不是从 System.Web.UI.MasterPage 继承,而是从您的 MasterPageBase 继承。覆盖继承页面中的虚拟方法。

public partial class MyMasterPage : MasterPageBase

在您需要引用它的 Class1 中(我假设您从 Page 类的 MasterPage 属性中获取母版页,您的代码将看起来像......

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

这是一个相当冗长的方法,但到目前为止,我能想到的唯一方法是考虑到 ASP.NET 模型。

于 2009-04-16T01:49:27.277 回答
1

尝试将母版页放在命名空间中

于 2009-04-16T01:31:18.317 回答
1

fung 有一个很好的建议,即使用基本页面。App_Code 文件存储在与 aspx 页面不同的程序集中。网站项目会发生这种情况。

我不确定您是否可以选择。但是,如果您选择 Web 应用程序项目而不是网站项目,那么您将不会遇到这个问题。

这里有一篇博文可能会有所启发: VS 2005 Web Project System:它是什么以及我们为什么要这样做?斯科特·格思里

于 2009-04-16T02:18:42.917 回答