ASP.NET Masterpage – Creating Masterpages in ASP.NET website:
ASP.NET Masterpage can be used to make a constant and consistent Web UI across all pages in your ASP.NET websites. They are supported in all .net framework and be added in every .NET websites.
Today let’s see how we can create a simple Masterpage in ASP.NET website and make its child pages or content pages.
Follow below steps :
Step 1 : Create a new ASP.NET website project in Visual studio. (I’m using Visual studio 2012 and you can also use your existing website of ASP.NET)
Visual Studio –
File > New > Website > ASP.NET Empty website.
Name your Project as MasterPage if you are creating a new one.
Step 2 : Making a Masterpage in ASP.NET website.
Your Project name > Add > Add New Item > MasterPage
Right Click on your Project in Solution explorer, click add > Add New Item Name > MasterPage. Name it as SitePage.master
Step 3 : Editing the content on Masterpage.
Edit your Masterpage as below :
SitePage.Master :
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="SitePage.master.cs" Inherits="SitePage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style> body { font-family: Arial; padding: 2px; } a { text-decoration: none; color: #252525; margin: 5px 20px 5px 0px; font-weight:bold; } .container { margin-top:10px; } </style> <asp:ContentPlaceHolder ID="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <h1>PARALLELCODES.COM</h1> <div style="width: 100%"> <a href="Home">Homepage</a> <a href="Post">Blog Post</a> <a href="About.aspx">About</a> <a href="Contact">Contact</a> </div> <hr /> <div class="container"> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form> </body> </html>
All our content will be placed with the ContentPlaceHolder tag of Masterpage under the body tag.
Step 4 : Adding new Content Pages.
Add two new pages with name :
- Home.aspx
- About.aspx
While adding new pages, please select , “Select Masterpage” option. And Edit them as below.
Home.aspx :
<%@ Page Title="" Language="C#" MasterPageFile="~/SitePage.master" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> This is my Homepage. </asp:Content>
About.aspx :
<%@ Page Title="" Language="C#" MasterPageFile="~/SitePage.master" AutoEventWireup="true" CodeFile="About.aspx.cs" Inherits="About" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> Hello, This is my post on ASP.NET Masterpage - Creating Masterpage in ASP.NET websites. </asp:Content>
Set Home.aspx as Start page.
And we’re ready to test our Masterpage.
.