Master Pages in ASP.Net 2.0

ASP.Net has provided us with powerful mechanisms to separate code and functionality from design and the user interface, by such concepts as web controls and code-behind. With ASP.Net 2.0, Microsoft has taken it up a notch, allowing us to completely separate the templates of the entire site from any code in individual pages, through a new concept called Master Pages.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 19
September 15, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Introduction

Generally speaking, web programmers are not designers. Not by a long shot. That’s the reason we love programmable web controls. We can insert them on the page, do all the programming around them in the code behind, and let the designer worry about how it all looks (without messing up our code!). It’s also why tools such as DreamWeaver are so popular. We can design templates, create pages based on those templates, modify only certain pieces of the page, and let DreamWeaver handle any updates to pages for which the template has been modified.

With old-school ASP, we used include files, and we used them nefariously. Every single navigation element and widget and snippet got thrown into an ASP page, and we would toss in our include statements all over the place, making it sometimes incredibly fun to find a programming error, or even a twice declared variable.

Then with ASP.Net 1.1, we had something of a mind-shift to object-oriented programming. Here we were able to plug in other server controls, HTML, and programmatic code, and encapsulate them all into one "user control." We could then plug that user control onto any number of pages in our application, and use that functionality all over the site. Of course, then you ran into somewhat serious issues when you needed to modify a user control. If you made any changes to the properties, methods, or events in a single user control, you would need to recompile all pages that used that control, as well as redeploy the entire assembly. And then the first visitor to the page gets the unwelcome surprise of waiting for the .Net runtime to recreate it.

So to not only address these issues, but also give the advantage of being able to template your entire site with one page, Microsoft has come up with Master Pages.

Master Pages – The Concept

A Master Page is more or less just a template, or a shell. In the Master Page, you will define the look and feel across your application, as well as the common controls and functionality that is needed (a date, a login indicator, and so forth). It is possible to define multiple master pages within one site/application. For example, you could have one template for your public website, and a completely separate template for the administrative content management system in the backend. You could even have a Master Page nested within another Master Page, but now that’s just crazy!

A "content" page is the actual page within the site that you’ll be working on, and it will inherit its UI from the Master Page. When the URL of the content page is called, ASP.Net merges the two in the background, and sends the results to the client, who of course will be completely unaware of the fancy process that just took place.

Master Pages – The Code

Working with Master Pages will offer a seriously difficult learning curve, as we have an outrageously high number of lines of code to learn and remember. In fact, we are tasked to learn all of two new lines of code.

  1. the first, a new directive, is this:<%@ Master %>
  2. the second, equally as daunting, is this:<asp:contentplaceholder />

Whew, that was tough! Maybe Microsoft should rethink and create a less complex system…

Okay, enough sarcasm. It’s actually that easy. In fact, here is all the code necessary to get a barebones Master Page up and running:

<%@ Master %>
<html>
<head>
    <link rel=”Stylesheet” href=”styles.css” />
</head>
<body>
      <img src=”logo.gif” />
      <form runat=”server”>
            <asp:contentplaceholder runat=”server”
id=”bodyContents”>
                  <p>default, replaceable content here</p>
            </asp:contentplaceholder>
      </form>
</body>
</html>

Then you simply save this file with a .master extension, and you’re ready to go! For our example we’ll leave it as the default ‘site.master’.

Worthy to note is that a Master Page in essence is simply an extended UserControl, so you have all of the same attributes available to the @Master directive as you would with the @Control directive.

Content Pages

To define and populate a content page, the process is equally as painless. In the @Page directive, you simply need to indicate which Master Page the content page uses. Then with the page, you implement any controls (content) by placing them inside a "content" control, and indicate which content placeholder you’re filling. So the content page could be as simple as the following:

<%@ Page Language=”C#” masterpagefile=”site.master” %>
<asp:content runat=”server” contentplaceholderID=”bodyContents”>
      <p>this is some content to replace the default content</p>
</asp:content>

So you could save this as default.aspx, run the application, and the result would be a merge of the master and content pages, with the logo and the new paragraph attached.

Something you may have noticed is that on default.aspx, I didn’t include the necessary <form runat=”server”> control. This may seem strange to you, but I assure you it’s not an error. The reason for this is that the form control is already implemented in the Master Page, and the result of the merging is that the content page inherits the form from its parent Master Page. It makes sense when you think about it!

But the whole point of ASP.Net is not to put up static content on the web, but to create dynamic pages. So how would you do that in a content page? Well, the programmatic code still exists outside of the layout, and your code will take the following form:

<%@ Page Language=”C#” masterpagefile=”site.master” %>
<script runat=”server”>
      void calcClicks(object sender, EventArgs e)
      {
            int count = int.Parse(clickedLbl.Text)
            clickedLbl.Text = count++;
      }
</script>
<asp:content runat=”server” contentplaceholderID=”bodyContents”>
      <p>this is some content to replace the default content</p>
      <asp:button runat=”server” id=”clickBtn” text=”click”
            Onclick=”calcClicks” /><br />
      This button has been clicked
      <asp:label id=”clickedLbl” runat=”server”>0</asp:label>
      times.
</asp:content>

So we’ve thrown in some fairly simplistic code to count how many times a button has been clicked. Not brain surgery, but at least you can see how in-page coding will work. And there is no change to the code-behind page, so if you’re accustomed to working with that, you have nothing to learn anew!

Going Beyond the Basics

There are many additional options we have with Master Pages, and I’ll highlight a few of what I believe to be the more useful ones.

Site-wide Definition

Something I could see becoming a pain is having to remember to reference the Master Page for every single content page in your site, especially if your application has many pages. Well of course the thoughtful ASP.Net team planned ahead to circumvent this issue, by allowing us to define a default Master Page for the entire application in the web.config file. To create this definition, you would place the following in the web.config file:

<configuration>
      <system.web>
            <pages masterpagefile=”site.master” />
      </system.web>
</configuration>

Client-side Scripting

This is more of a caveat than anything. Quite often we developers will implement some custom client-side JavaScript to manipulate the contents of our controls without having to perform a post back to the server. A good example of this would be a timesheet, for which you create JavaScript code that changes totals in real time as you enter your hours, and then checks and saves the values once you’re done and hit submit.

When not using Master Pages, it’s quite simple to do this, because all of your web controls have an id parameter, and that id is transmitted when the HTML control is created. Therefore all you need to do is reference the ID of the object in JavaScript as you would in any HTML page.

When I created my first Master/Content pages, I was annoyed to see that all of my client-side script "broke." As soon as I checked the generated source code, it was easy to see why. Every control id had been changed. Each still contained the original id, but now they had appended to the beginning a string something like the following: “_ctrl105_”.

To fix any broken JavaScript references, what you’ll need to do is examine your browser’s source code, find what the appended string is in your case, and tell your JavaScript code to add it to the beginning of any object references it’s using.

Customized Master Pages

While the major browser creators still struggle to come to terms with complete standards compliance, there remains the possibility that we as developers may need to customize the UI somewhat to meet any inconsistencies. Coincidentally, the Microsoft team has allowed us to create different Master Pages for different browsers. You can form your own conclusions about the reasons why, I’m only here to show you how to do it!

So we could take our standard Master Page reference:

<%@ Page masterpagefile=”site.master” %>

And we could tweak it to provide a Firefox friendly alternative:

<%@ Page netscape:masterpagefile=”nsSite.master” masterpagefile=”site.master” %>

And then even further to customize for Internet Explorer as well:

<%@ Page netscape:masterpagefile=”nsSite.master”
ie:masterpagefile=”ieSite.master” masterpagefile=”site.master” %>

While you as a developer and a believer in web standards may grimace at the idea of creating separate templates for separate browsers, this is a still a good example of how flexible Master Pages are, even in their first revision!

Conclusion

Master Pages in my opinion will be enormously popular, among developers and designers alike. Another forward stride in the world of Rapid Application Development, I really have to hand it to the ASP.Net team on this one! I hope that with the assistance of this article, you will find them enjoyable to use, flexible, and simple to work with.

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 4 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials