Master Page and PreInit
Emil Stoichev reminded today that it is very important to understand what is ViewState, how it works and how we should use it. The other problem mentioned there is unavailability of controls in PreInit phase if MasterPage is used.
The problem is very simple. If you have the following content page (in master page),
<%@
Page
Language="C#"
MasterPageFile="~/MasterPage.master"
Title="Page"
%>
<asp:Content
ID="Content1"
ContentPlaceHolderID="ContentPlaceHolder1"
runat="Server">
<p>Content</p>
<p><asp:Label
runat="server"
ID="ContentPageLabel"
/></p>
</asp:Content>
<script
runat="server">
protected
override
void OnPreInit(EventArgs
e)
{
base.OnPreInit(e);
// next line crashes
ContentPageLabel.Text =
"Hello, World!";
}
</script>
it crashes on the label text assignment with:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
|
I had to solve this problem some time ago,and I found that once you access the Master property of you content page for the first time all controls become instantiated.
So, adding just a single line of code before label text assignment fixes the problem.
<%@
Page
Language="C#"
MasterPageFile="~/MasterPage.master"
Title="Untitled Page"
%>
<asp:Content
ID="Content1"
ContentPlaceHolderID="ContentPlaceHolder1"
runat="Server">
<p>Content</p>
<p><asp:Label
runat="server"
ID="ContentPageLabel"
/></p>
</asp:Content>
<script
runat="server">
protected
override
void OnPreInit(EventArgs
e)
{
base.OnPreInit(e);
// the following line is important
MasterPage master =
this.Master;
// unfortunately, compiler warns us that master is
not used
ContentPageLabel.Text =
"Hello, World!";
}
</script>
Note that everything works like without MasterPage with this small change.