Tuesday, April 28, 2015

ASP.Net C# Accessing Master Page Controls from Content Pages

This is a pretty simple task, but one I use frequently. Often times I have controls in my master page that I want to access or somehow control differently from page to page. So here is a very simple example of how to accomplish that.

Base.Master
   <asp:PlaceHolder id="pnlDoNotIndex" visible="false" runat="server">  
     <meta name="robots" content="noindex" />  
   </asp:PlaceHolder>  

Base.Master.cs
     public bool DoNotIndex
     {  
       get { return pnlDoNotIndex.Visible; }  
       set { pnlDoNotIndex.Visible = value; }  
     }  

Test.aspx
 <%@ Page Language="C#" MasterPageFile="~/Base.Master" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Sandbox.Web.Test" %>  
 <%@ MasterType VirtualPath="~/Base.master" %>  

Test.aspx.cs
     private void Page_PreInit(object sender, System.EventArgs e)  
     {  
       // do not index
       Master.DoNotIndex = false;  
     }  

The MasterType declaration provides a way to create a strongly typed reference to the ASP.NET master page when the master page is accessed from the Master property. That allows us to just say Master.DoNotIndex to get/set the publicly exposed property.

Like I said, this example is as simple as it gets, but it allows you to make your master page more generic and only expose the pieces you need from page to page.

Lastly, the reason I prefer an approach like this for the "robots" tag is because it allows me to standardize on a single tag throughout the entire web application to indicate whether or not the page is crawlable or not. An alternative would be to use an asp:ContentPlaceHolder in your master page, and then set the content for it from page to page as needed. I'm not opposed to that solution, and in fact I use that approach quite often for various things, but it really depends on what you are trying to expose and how generic you are trying to keep it. In this case I wanted a single uniform "robots" tag to be defined to not allow a page to be indexed, and if that "robots" tag ever needed to change, I could do that in one place, opposed to each individual content page that had defined it separately.

Matt Pavey is a Microsoft Certified software developer who specializes in ASP.Net, VB.Net, C#, AJAX, LINQ, XML, XSL, Web Services, SQL, jQuery, and more. Follow on Twitter @matthewpavey

0 comments: