UPDATE: I've been experimenting with my controls some more and I think I've gotten closer. Please read on for updated info.
I have 2 ASP.NET 2.0 user controls, one of which is placed inside of the other one. Inside of the inner control I have an HtmlAnchor
tag control which I'm trying to set a URL for from the outer control. When I attempt to set the HRef
property from the rendering page's markup, the HtmlAnchor
control is null
and throws an exception.
The URL set
property is being called before the OnInit event of either the inner or the outer control and before the main Page's 'OnPreInit
' event. I'm assuming this is because I am setting the URL of the child control in the markup of the parent control on the page I'm rendering the controls on which means the value is set before OnInit()
. Here is the (stripped down) version of the code I'm using:
[ParseChildren(true)]// <- Setting this to false makes the
// page render without an exception
// but ignores anything in the markup.
[PersistChildren(false)]
public partial class OuterControl : System.Web.UI.UserControl
{
// The private '_Inner' control is declared
// in the .ascx markup of the control
[PersistenceMode(PersistenceMode.InnerProperty)]
public InnerControl Inner
{
get{ return _Inner; }
set{ _Inner = value; }
}
}
public partial class InnerControl : System.Web.UI.UserControl
{
// The private 'linkHref' control is declared
// in the .ascx markup of the control
public string Url
{
get { return linkHref.HRef; }
set { linkHref.HRef = value; }
}
}
The OuterControl is used on my Default.aspx page like this:
<uc1:OuterControl ID="OuterCtrl1" runat="server">
<Inner Url="#" />
</uc1:OuterControl>
In the markup example above, if I try to render this page an exception gets thrown because the linkHref
control is null. Using my debugger I can see that every control within the InnerControl is null, but both the InnerControl & OuterControl's OnInit()
event has not been triggered yet when the Url
property is accessed.
UPDATE
I thought adding the attributes 'ParseChildren
' and 'PersistChildren
' would help. I've used them in Server Controls before but never in User Controls, although the effect seems to be similar. I don't think I'm interpreting the documentation for these two properties correctly, but it can stop exceptions from being thrown. The page markup becomes ignored though.
Does anyone know a way to have this work. I don't understand why these controls are getting values set before OnInit()
. When I try to set their values using the ASPX markup, the constructor for the InnerControl
is being called twice. Once to set the values based on the markup (I'm assuming) and again on OnInit()
(which I'm guessing is why the markup values are getting ignored).
Is this effort hopeless or am I just approaching it from the wrong angle?