R – Proper use of MasterPages

asp.netmaster-pages

I've been looking into different methods of implementing masterpages.

  1. Use the masterpage only for layout, include common controls on every page
  2. Include controls on the masterpage, use a masterpage abstract base class and override it's properties in the masterpage class. This caused the masterpage events to no longer wire up. I could probably fix this, but it's a long way to go just for a single textbox value.
  3. use good 'ol Page.Master.FindControl()

I've read that findcontrol should be avoided (uses magic "label1" strings, supposedly uses too many resources) and masterpages are only for layout. If masterpages are only for layout, do I copy and paste common controls across 100's of pages?

What's the best practice that deals with displaying and accessing common site controls (like a search)? Considering the alternatives, using findcontrol to get a masterpage control doesn't seem that bad.

Best Answer

MasterPages are classes just like a normal Page object. That means you can expose internal controls through public properties to allow child Pages to access without having to resort to Master.FindControl(). To do this you just need to set the MasterType property in the page (I think it may work even without setting this but with this you get intellisense support and avoid having to do casts).

Here's a basic example (sorry it's in VB - this is copying and pasting from an old project):

Master page (.master):

<%@ Master Language="VB" CodeFile="default.master.vb" Inherits="DefaultMaster" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form runat="server">
    <ASP:TextBox ID="Search" RunAt="Server"/>
    <ASP:ContentPlaceHolder ID="Content" RunAt="Server"/>
    </form>
</body>
</html>

Master code-behind (.master.vb):

Partial Class DefaultMaster : Inherits MasterPage
    Public ReadOnly Property SearchBox() As TextBox
        Get
            Return Search
        End Get
    End Property
End Class

Accessing page (.aspx):

<%@ Page Language="VB" MasterPageFile="default.master" CodeFile="page.aspx.vb" Inherits="ExamplePage" %>
<%@ MasterType TypeName="DefaultMaster" %>

<ASP:Content ContentPlaceHolderID="Content" RunAt="Server">
    <p>This is some content on the page.</p>
</ASP:Content>

Accessing page code-behind (.aspx.vb):

Partial Class ExamplePage : Inherits Page
    Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs) Handles MyBase.Load
        Master.SearchBox.Text = "This page now has access to the master's search box."
    End Sub
End Class
Related Topic