ASP.NET: How to Convert Your Site To A MasterPage Site in 3 Steps
Once you have your design converted into HTML/CSS, why should you have to worry about breaking it every time you create a new page? Abstract yourself from this with MasterPages, while still enabling yourself to easily make design changes. MasterPages are wonderful for standardizing your site and your design, in addition to making it easier to maintain and to build new pages. They are a very powerful and easily customizable way to template your site. This article is for those who don’t have much or any experience with MasterPages or are converting an old ASP.NET site to a MasterPage-driven site. If this is you, don’t be afraid—You can do it in just three easy steps!
1. Create a new MasterPage
Right click your project, go to “Add” and then “New Item…” and select MasterPage. Name it something useful, like “main.master” and hit ok. You should be presented with a barebones XHTML skeleton. Notice that your skeleton has this tag in it:
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server" />. This is the location where your content will be loaded from your .aspx pages. Fill your new MasterPage with the XHTML that you wish to use on every page. If you want some things to change based on certain variables, you can do so in the codebehind. Treat the MasterPage like any other .aspx page. The only thing different about it (on a basic level) is that it does not contain your content, but rather what encompasses your content.
2. Link your old pages to your MasterPage in the Page Directive
In your <%@ Page directive, add the following attribute:
3. Tell the MasterPage What Content Goes Where
If you only have one ContentPlaceHolder, you will add the following tag around all of your content in your .aspx pages:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">Hello, World!
</asp:Content>, where “ContentPlaceHolder1” is the ID of the placeholder in your MasterPage that you linked to in step 2. If you have more than one ContentPlaceHolder in your MasterPage, simply wrap the tags around the correlating content.
And that’s it! That’s really all there is to it! Just apply steps 2 and 3 to each of your .aspx pages. There is an optional step for those who may have changed their pages’ codebehind inheritance:
4. Change CodeFile Inheritance
Simply replace whatever inheritance you have with
Please read my articles ASP.NET: How To Easily Reference MasterPage Members and my ASP.NET and AJAX: So Freaking Easy series for more tips on how to get yourself set up even better using MasterPages.