Master Page Properties Exposing in ASP.NET

Introduction

There is very good feature available in Visual Studio that we can expose properties and methods from a Master Page and modify the properties and methods from a particular content page. For example, the Master Page given below includes a public property named BodyTitle.

Master Page File Code

<%@ Master Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Public Property MasterBodyTitle() As String
        Get
            Return ltlMasterBodyTitle.Text
        End Get
        Set(ByVal Value As String)
            ltlMasterBodyTitle.Text = Value
        End Set
    End Property

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <style type="text/css">
        html
        {
            background-color:silver;
        }
        .content
        {
            margin:auto;
            width:700px;
            background-color:white;
            padding:10px;
        }
        h1
        {
            border:3px dotted blue;
        }
    </style>
    <title>Master Page Properties Exposing</title>
</head>
<
body>
    <form id="form1" runat="server">

    <div class="content">

    <h1><asp:Literal ID="ltlMasterBodyTitle" runat="server" /></h1>

        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>
    </div>

    </form>
</body>
</
html>


Default.aspx File Code

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" %>

<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        If Not Page.IsPostBack Then
            Master. MasterBodyTitle= "The Body Title"
        End If
   End Sub

 </script>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
There is some data for the page.
</asp:Content>


We can notice several things in above codes. First, notice that we can refer to the Master Page by using the Master property. In the Page_Load() method in Default.aspx file code. The MasterBodyTitle property of the Master Page is assigned a value with the following line of code:

Master.MasterBodyTitle = "The Body Title"

We also notice that Master Page File includes a <%@ MasterType %> directive. This directive automatically casts the value of the Master property to the type of the Master Page. In other words, it casts the Master Page to the PropertyMaster type instead of the generic MasterPage type. If we want to be able to refer to a custom property in a Master Page, such as the MasterBodyTitle property, then the value of the Master property must be cast to the right type. The MasterBodyTitle property is not a property of the generic MasterPage class, but it is a property of the PropertyMaster class.

HAVE A GREAT CODING!

Up Next
    Ebook Download
    View all
    Learn
    View all