我有一个简单的嵌套母版层次结构。 但是,在运行时,母版页控件(以label1为例)始终为null。
如果Default.aspx
更改为直接使用Base.master
,则会正确定义母版页控件。
这种行为的原因是什么?
Base.master
<%@ Master Language="C#" CodeFile="Base.master.cs" Inherits="BaseMaster" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server"></head>
<body>
<form runat="server">
<asp:Label runat="server" id="label1" Text="Label 1" />
<asp:ContentPlaceHolder runat="server" ID="MainContent" />
</form>
</body>
</html>
Base.master.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class BaseMaster : MasterPage
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
label1.Text = "Base"; // Causes NullReferenceException
}
}
Sub.master
<%@ Master Language="C#" CodeFile="Sub.master.cs" Inherits="SubMaster" MasterPageFile="~/Base.master" CodeFileBaseClass="BaseMaster" %>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<asp:ContentPlaceHolder runat="server" ID="SubMainContent" />
</asp:Content>
Sub.master.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SubMaster : BaseMaster
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
label1.Text = "Sub"; // Causes NullReferenceException
}
}
Default.aspx的
<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="DefaultPage" MasterPageFile="~/Sub.master" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="SubMainContent">
<h3>Default</h3>
</asp:Content>
Default.aspx.cs
using System;
using System.Web;
using System.Web.UI;
public partial class DefaultPage : Page
{
}