I absolutely adore the master pages feature in ASP.NET 2.0, which is basically a very advanced templating system.
Having found the answers, I thought I’d be a good netizen and share them with you.
Thus, your master page’s head block would look something like this:
<head runat="server"> <asp:ContentPlaceHolder ID="cphJS" runat="server" /> </head>
It’s worth noting that Microsoft does not recommend this methodology, and if you use Microsoft’s IDEs (e.g., Visual Web Developer, Visual Studio), they will issue a warning that ContentPlaceHolders are not allowed in the head section of a master page.
Problem 2: Triggering the onLoad event from the content page
There’s two good things about ASP.NET 2.0 that really work out for us here. The master page / content page system is one of classes and subclasses, so what we do on a content page can impact the master page; and ASP.NET allows us to treat any XHTML tag as an object, so we can programmatically change their attributes however and whenever we want.
First, we need to provide a specific ID to the body tag, and indicate that we want it to run at the server, the same way the head tag is set to run at the server by default when we create an ASP.NET 2.0 page in a Microsoft IDE.
So, our master page will now have a body tag such as this:
<body runat="server" id="htmBody">
Having assigned our body tag an ID and the runat=”server” attribute, we can now bring in the HTML namespace, which we’ll need if we’re going to programmatically change the tag. That namespace is System.Web.UI.HtmlControls. If you use the Microsoft IDEs, this library should be included, by default, in your web.config file. If not, you either can add the namespace to your web.config file’s namespaces section, or to the content page’s namespaces via the @Import directive.
To add the onLoad event to the body tag in our content page, we just need to add the attribute via the Page_Load subroutine on the content page. At compile time, ASP.NET makes a master class from the master page, and creates child classes from the content page; thus, anything we have on the master page, we can control from the content page!
So, we add this subroutine to our content page [The code below is in VB.NET].
This subroutine does the following:
- Finds the body tag in the master page, using the very handy FindControl method, and the name we provided to the tag;
Sub Page_Load(Sender As Object, E As EventArgs) Dim objBody As HtmlGenericControl = Page.Master.FindControl("htmBody") objBody.Attributes.Add("onload", "doItOnLoad();") End Sub
Again, you can see this in action at the MELMAC Education Foundation’s Contact Us / Directions page.
If you found this helpful, or have questions, please leave a comment.