Welcome!

.NET Authors: Sandi Mappic, Ivan Antsipau, JP Morgenthal, Yeshim Deniz, Carmen Gonzalez

Related Topics: .NET

.NET: Article

Master Pages in ASP.NET 2.0

Simplify reuse and maintenance

Since the advent of Web development, Web developers have sought a way to provide a consistent look and feel across the Web application. This pursuit has resulted in different custom solutions. With the introduction of master pages in ASP.NET 2.0, Microsoft has finally brought the support to the framework level and has given the developers what they have been asking for. Master pages, as the name suggests, allow the developer to define the layout in a single page and easily apply the layout to multiple pages across the Web site, thereby ensuring a consistent appearance. This article looks at how we use master pages with the help of some examples. We will also look at some of the new features that are available in ASP.NET 2.0.

Master Pages
Master pages allow the developer to take a compartmentalized approach while developing Web sites. It allows the developer to move standardized layouts like header, footer, navigation, or any other content that is common over multiple pages to the master page. Content that is specific to a particular page can be defined in content pages that we will see in the next section. Master pages are transparent to the users and when a request is made to the URL of the content page, ASP.NET merges the content of the content page with that of the master page and renders the resulting page. Unlike ordinary ASPX pages, a Web server does not serve a master page and if a user makes a request to the master page, the server returns an error message (see Figure 1).

Master pages are like any other ASP.NET pages with a couple of exceptions. They are identified by a .master file extension. Listing 1 (the code is online at www.sys-con.com/dotnet/source.cfm) is an example of a simple master page. Note that instead of the familiar page directive <%@Page%> in a normal ASPX page, the master page has a <%@Master %> directive. Master pages define ContentPlaceholder controls that act as placeholders where content from the content page will be inserted. ContentPlaceholder control is specific to master pages and cannot be declared in a content page. In this example we have defined one ContentPlaceholder control identified as ContentPlaceholder1. A master page can define zero to any number of ContentPlaceholder controls.

Content Pages
The content page is the actual page that a user will request from the server. Content pages are like typical ASPX pages and have a .ASPX extension. However, they differ from an ordinary ASPX page in two ways. The first difference is that a content page has to be associated with a master page, which is done by setting the MasterPageFile attribute in the page directive. Second, all of the content in a Web page must be defined inside a new content control. Any content that is defined outside the content control results in an error. The content control in turn has to be mapped to the Contentplaceholder controls that have been defined in the Master page. Listing 2 shows a content page that refers to Sample.master as its master page. In this example the content page defines a content control called Content1. This content control in turn is mapped to the ContentPlaceholder ContentPlaceHolder1 of the master page by setting the ContentPlaceHolderID.

Sequence of Events
Just like regular ASPX pages, master pages and content pages have events that are fired during the page life cycle. They can also have user controls that need to be initialized. The list below shows the sequence of events in a content page that references a master page.

  1. Controls in the master page are initialized
  2. Controls in the content page are initialized
  3. Master page is initialized
  4. Content page is initialized
  5. Content page loads
  6. Master page loads
  7. Master page controls load
  8. Content page controls load
Creating a Master Page and a Content Page
Now that we have seen what a master page and a content page are, let's see how to create a master and content page using Visual Studio .NET 2005 Beta. Visual Studio allows us to add master pages by choosing an item of type Master Page in the Add New Item option. It also gives us the option to have a code behind page associated with the master page and also select the language of the page. In Figure 2, I add a master page called MyMaster1.master using the Add New Item dialog.

To the master page that I just created, I have added an image, footer, and two content placeholders. Each of the ContentPlaceholder controls that has been added has a unique ID which will be referred to by the content page to insert its content. Listing 3 shows the markup and Figure 3 shows the design view of the master page that I have created. Any content page that uses this master page will automatically inherit the image, the heading, and the footer.

Now that we have created the master page, let's go ahead and create a content page using the Add New Item option in Visual Studio .NET 2005 Beta (see Figure 4). A content page is just an ordinary Web form and Visual Studio .NET 2005 Beta does not have a special type called content page. When we create the content page, the Add New Item dialog, however, gives us the option to select the master page that will be referenced by the Web form. Once we select this option, Visual Studio presents us with a dialog box that lists all the master pages in the Web site (see Figure 5). Figure 6 shows the design view of the content page that we have just created. You will notice that all the master page content is grayed out and cannot be edited. Listing 4 shows the markup of the content page we just created. The only editable portion in the content page is between the <asp:Content> tags. Each of these content tags is linked to ContentPlaceholder of the master page by setting the ContentPlaceHolderID for the content control. In Listing 4, Content1 is mapped to ContentPlaceholder1 of the master page and Content2 is mapped to ContentPlaceholder2 of the master page. Content control in turn can contain other controls. In this example I have added some text in each of the content tags. Figure 7 shows the browser rendering of the content page.

Nesting Master Pages
Master pages can be nested and can have one master page refer to another as its master. Nested master pages are very useful while designing Web sites with different sections where each individual section has to have its own layout and at the same time be consistent with the overall appearance of the Web site. For example, in a corporate Web site we could have a master page that could define the global menu and a master page for each department that would define the departmental menu. Nesting the department master page and the corporate master page would allow us to combine the two menus. Visual Studio .NET 2005 Beta, however, does not provide designer support for nested master pages.

Let's look at how to create a nested master page with the help of an example. Listing 5 shows the parent master page, ParentMaster.master. This parent master page is then referred to by the child master page (see Listing 6). As you can see, the child master page is not very different from the parent master page. They have the same .master extension; however, the child master page has a content control that is mapped to the ContentPlaceHolder control defined in the parent master page. The child master page can also define ContentPlaceHolder controls of its own to display content of the content page that refers to this page as its master. The child master page in our example defines a content control that is mapped to ContentPlaceHolder1 of the master page. It defines a Contentplaceholder control of its own ChildContentPlaceHolder1 to which the content page will map its content. Listing 7 is the content page that refers to the child master page as its master page. Figure 8 shows the rendering of the content page that uses nested master pages.

Configuring a Site to Use Master Pages
Instead of giving the master attribute in the page directive of each and every page in a Website, ASP.NET 2.0 gives you the option to set the master page in the Web.config file. This is very useful in large Web sites as it gives the developers the flexibility to make the change at one place and apply it across the site. The code snippet below shows how to set the master page in the web.config file:

<system.web>
<pages masterPageFile="MyMaster1.master" />
</system.web>

A couple of things need to be pointed out about setting master pages through the web.config file. First, if the content page has a master page explicitly set in its page directive, that master page assumes precedence over the one set in the web.config file. If there are multiple master page settings in different web.config files, the master page setting in the immediate folder overrides the other setting similar to how in an application with multiple sub- folders, the setting of the web config in the immediate folder takes precedence over the others.

Accessing Master Page Controls from Content Pages
The developer may need to access the controls in the master page for many reasons. One could be to display a value that is relevant to the content page. ASP.NET 2.0 gives you multiple options to achieve this. The first step is to get a reference to the master page. In a content page, the Master property returns the reference to the master page. Once we have obtained the reference to the master page, it is now possible to refer to the controls of the master page. We will look at two approaches. The first approach is early binding, where the control is declared as a public property in the master page. Listing 8 shows the master page where we first expose the text of control Label2 as a public property LabelText. We then access and set the value of LabelText in the page load event of the content page as shown in Listing 9. Another thing to point out is the strong typed reference to the Master page using the <%@masterType%> directive in the Content page. This explicitly casts the value of the master property to the master page object which in our case is AccessMasterProperties.

The second approach is the late binding approach. Here we make use of the familiar FindControl method. We get a reference to a label control in the master page and change the text value from the content page. We search for the label by its ID which in this case is Label1 and then cast it to a label control and set the value for the text.

Dynamically Changing Master Pages
ASP.NET 2.0 allows the developer to change the master page associated with a content page dynamically at run-time. This is very useful if the developer would like to give the users the flexibility of choosing the master pages. The master page for a content page can be set programmatically by assigning a value to the MasterPagefile property of the page. However, this dynamic assignment can be done only in the preinit event of the content page since this is the earliest event that occurs in the page execution life cycle. If we attempt to set the master page file in events like pageload, it would result in an exception. Listing 10 shows an example where we have a dropdown list with the available master pages. On clicking the button we redirect the response to the same page and pass the value of the master page to be set as a request string. The MasterPagefile is then set in the preinit event.

Device-Specific Master Pages
ASP.NET 2.0 pages and controls have built-in support that enables them to automatically render appropriate content depending on the browser and the device that has requested the page. Master pages also support similar behavior. We can create a master page specifically for a device or a browser and in the content page instead of binding to a single master page. We can bind them to number of master pages, each of them specific to a particular device. The binding is qualified with the device name. Listing 11 shows a content page that is bound to two master pages, one for Internet explorer and another for mozilla. The Internet Explorer master page is prefixed with ie and the one for Mozilla is prefixed with Mozilla. These browser prefixes are defined in the browsercaps section of the machine.config file. Depending upon the browser requesting the page, the content page is bound to the appropriate master page. Figures 9 and 10 show the rendering of the content page when it is requested through the two different browsers, Mozilla and Internet Explorer. As you see, ASP.NET 2.0 has automatically chosen the appropriate master page.

Conclusion
In this article we looked at the concept of master pages and saw how they allow the developer to easily create reusable page layouts. It also greatly simplifies maintenance as it is now possible to make changes at one place and propagate them throughout the Web site. I am sure that this feature will have a significant impact on how ASP.NET applications are built in the future.

More Stories By Jeevan Murkoth

Jeevan Murkoth is a Microsoft Certified Solutions Developer (MCSD) in .NET (Early Achiever) and a Microsoft Certified Application Developer (MCAD) in .NET. He currently consults for Tennessee Valley Authority and lives in Chattanooga, TN. He has an MS in Management Information Systems from Texas Tech University.

Comments (1)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, will describe how to revoluti...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.