我目前遇到了一个奇怪的问题。首先,我的代码剪断了:
// This is my base page class
public class MyBasePage
{
protected override void InitializeCulture()
{
base.InitializeCulture();
MasterPage master = Page.Master; // point1
}
}
// This is my page
public partial class Default : MyBasePage
{
protected void Page_Load(object sender, EventArgs e)
{
label1.Text = "Test"; // point2
}
}
通常,point2上的label1不是NULL。但是如果我在InitializeCulture()事件(point1)中访问母版页,那就是。有人为了解释原因吗?
我想我必须找到另一种解决方法,这对我来说没问题。但我想了解那里发生了什么。
答案 0 :(得分:0)
这是因为主页和主题在初始化期间应用于页面,并且在此之前调用InitializeCulture,因此它返回null。
答案 1 :(得分:0)
我用ILSpy分析了这种行为。问题是,母版页未在InitializeCulture事件中初始化,如果被访问,它将被初始化 - 但显然不正确。
结论:永远不要从InitializeCulture事件访问母版页 - 它会搞乱页面初始化过程。
这里,仅供参考,初始化母版页的.NET代码:
internal static MasterPage CreateMaster(TemplateControl owner, HttpContext context, VirtualPath masterPageFile, IDictionary contentTemplateCollection)
{
MasterPage masterPage = null;
if (masterPageFile == null)
{
if (contentTemplateCollection != null && contentTemplateCollection.Count > 0)
{
throw new HttpException(SR.GetString("Content_only_allowed_in_content_page"));
}
return null;
}
else
{
VirtualPath virtualPath = VirtualPathProvider.CombineVirtualPathsInternal(owner.TemplateControlVirtualPath, masterPageFile);
ITypedWebObjectFactory typedWebObjectFactory = (ITypedWebObjectFactory)BuildManager.GetVPathBuildResult(context, virtualPath);
if (!typeof(MasterPage).IsAssignableFrom(typedWebObjectFactory.InstantiatedType))
{
throw new HttpException(SR.GetString("Invalid_master_base", new object[]
{
masterPageFile
}));
}
masterPage = (MasterPage)typedWebObjectFactory.CreateInstance();
masterPage.TemplateControlVirtualPath = virtualPath;
if (owner.HasControls())
{
foreach (Control control in owner.Controls)
{
LiteralControl literalControl = control as LiteralControl;
if (literalControl == null || Util.FirstNonWhiteSpaceIndex(literalControl.Text) >= 0)
{
throw new HttpException(SR.GetString("Content_allowed_in_top_level_only"));
}
}
owner.Controls.Clear();
}
if (owner.Controls.IsReadOnly)
{
throw new HttpException(SR.GetString("MasterPage_Cannot_ApplyTo_ReadOnly_Collection"));
}
if (contentTemplateCollection != null)
{
foreach (string text in contentTemplateCollection.Keys)
{
if (!masterPage.ContentPlaceHolders.Contains(text.ToLower(CultureInfo.InvariantCulture)))
{
throw new HttpException(SR.GetString("MasterPage_doesnt_have_contentplaceholder", new object[]
{
text,
masterPageFile
}));
}
}
masterPage._contentTemplates = contentTemplateCollection;
}
masterPage._ownerControl = owner;
masterPage.InitializeAsUserControl(owner.Page);
owner.Controls.Add(masterPage);
return masterPage;
}
}