Team LiB
Previous Section Next Section

Master Pages and User Controls

At first glance, it seems to be strange, but it's actually possible to combine user controls and Master Pages without limitations and with the aim of reusing existing layouts. Therefore, the @Control directive offers a "master" attribute similar to @Page.

The sample in Listing 4-6 shows such an approach in combination with Master Pages, a user control, and a page putting it all together. The Master Page contains a table with two ContentPlaceHolder controls in it. Those are filled through the user control. As you can see from Figure 4-7, all elements are displayed correctly. Of course, you could also think about adding a Master Page for the page itself.

Click To expand
Figure 4-7: Gosh—it works!
Listing 4-6: Combining User Controls and Master Pages
Start example
// UCMaster.master
<%@ master language="C#" %>

<table id="Table1" bordercolor="black" cellspacing="1" cellpadding="1" width="100%"
    border="2">
    <tr>
       <td>
           <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
           </asp:contentplaceholder>
       </td>
       <td>
       </td>
       <td>
       </td>
    </tr>
    <tr>
       <td>
       </td>
       <td>This is my Master Page!</td>
       <td>
       </td>
    </tr>
    <tr>
       <td>
       </td>
       <td>
       </td>
       <td>
           <asp:contentplaceholder id="ContentPlaceHolder2" runat="server">
           </asp:contentplaceholder>
       </td>
    </tr>
</table>

// UCMaster.ascx
<%@ control language="C#" classname="UCMaster" master="~/UCMaster.master" %>

<asp:content id="Content1"
    contentplaceholderid="ContentPlaceHolder1"
    runat="server">
    This is my User Control
</asp:content>
<asp:content id="Content2"
    contentplaceholderid="ContentPlaceHolder2"
    runat="server">
    This is my User Control, too
</asp:content>

// UCMaster.aspx
<%@ page language="C#" %>
<%@ register tagprefix="uc1" tagname="UCMaster" src="~/UCMaster.ascx" %>

<script runat="server">

</script>

<html>
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form runat="server">
        <p>This text is embedded in the page itself.</p>
        <uc1:ucmaster id="UCMaster1" runat="server"></uc1:ucmaster>
        <p>This text is again embedded in the page.</p>
    </form>
</body>
</html>
End example

Team LiB
Previous Section Next Section