ASP.NET - 如何引用不在 app_code 中的类
我创建了一个名为 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?)
我需要添加哪些代码才能使其正常工作?
这些类位于以下文件夹中:
alt text http://www.yart.com。 au/stackoverflow/masterclass.png
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 http://www.yart.com.au/stackoverflow/masterclass.png
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将无法引用 MyMasterPage,除非您也将其放在 App_Code 下。 通常在这种情况下,您将创建一个继承自 MasterPage 的基本母版页。 例如,
然后在您的实际母版页中,不要从 System.Web.UI.MasterPage 继承,而是从 MasterPageBase 继承。 覆盖继承页面中的虚拟方法。
在 Class1 中,您需要引用它(我假设您从 Page 类的 MasterPage 属性获取母版页,您的代码将如下所示......
这是一个相当冗长的方法,但到目前为止我唯一知道的可以认为在 ASP.NET 模型下这是可行的。
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.
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.
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...
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.
尝试将母版页放入命名空间中
Try putting your master page in a namespace
fung 有一个很好的建议,即使用基本页面。 App_Code 文件存储在与 aspx 页面不同的程序集中。 网站项目会发生这种情况。
我不确定你的情况是否有这个选择。 但如果您选择Web应用程序项目而不是网站项目,那么您就不会遇到这个问题。
这是一篇博客文章,可能会有所启发: VS 2005 Web项目系统:它是什么以及我们为什么这样做? 作者:斯科特·格思里
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