Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Advanced Web Programming Chapter 8
1. Chapter8
Styles, Themes and
Master Pages
Chapter Outline
8.1 Styles
8.2 Themes
8.3 Master Page Basics
8.4 Advanced Master Pages
8.5 Questions
8.1 Styles
In the early days ofthe Internet, website designers used the formatting features of HTM
decorate these pages. These formatting features were limited, inconsistent, and sometimes o
supported. Worst of all, HTML formatting led to horribly messy markup, with formatting deta
littered everywhere.
The solution is the CSS standard, which is supported (with some discrepancies) in all moder
browsers. Essentially, CSS gives you a wide range of consistent formatting properties that you ca
apply to any HTML element. Styles allow you to add borders, set font details, change colors, ad
margin space and padding, and so on. Many of the examples you've seen so far have in this book ha:
used CSS formatting.
CSS and Types of the CSS
CSS stands for Cascading Style Sheets. It is generally used to display HTML in vario
views. It is used to design the view for HTML. CSS is a combination of a selector and
declaration.
What is the Selector and Declaration?
A selector is a HTML tag to for a style and a declaration is a combination ofthe proper;
and a value.
The Declaration's Property is predefined and the value is dependent on our requirement5,
we have a number of properties then we can separate them by a colon if we want to
des
the font color, back color and font size. For this we have a number of CSS properties. 1
way to specify them ín CSS is to separate them by a colon.
2. 221
Styles, ThemesandMasterPages
h3 tyie "font-familyadlal
Selector Property Value
Declaration
What is the Need for CSS?
HTML pages use a lot of markup to style the pages. There can be very complex structures o
tables, nested frames, invisible pixel images for layout, etc. This makes HTML page difficult to render
for the browser.
Advantages of CSS
Code: CSS is the standard forcoding in HTML. CSS is compatible with most browses CSS
reduces the length of the codes of web page, which decreases the page size, making it easy
and fast to load in browsers.
Design: Use of CSS makes the design simple. CSS makes the management of the entie
website easy to maintain byjust changing the CSS file which contains the style details.
Bandwidth: CSS reduces the HTML coding and page size. This reduces the bandwidth
usage.
Consistency: It is easy to maintain, handle and control the whole website made on CSS
based HTML. Ex: Suppose we want to change the background of the entire website, we just
need to change the background of the single page in the style sheet and the background of
the whole website will change.
CSS Selectors
Selectors
As its name implies, a selector is used to select or point to one or more specific elements within
your page. A number of different selectors are available, giving you fine control over what elements
you want to style.
The selector answers the first question: What element of the page must be styled?
Important Types of Selectors
The Universal Selector
The Universal selector, indicated by an asterisk ("), applies to all elements in your page. The
Universal selector can be used to set global settings like a font family. The following rule set changes
the font for all elements in your page to Arial:
3. Advanced Web Programmina
222
font-family: Arial;
The Type selector enables you to point to an HTML clement ofa specific typc. With a
selector, all HTML clements of that type will be styled accordingly.
The Type Selector
h1
color: Green;
This Type selector now applies to all <hl> elements in your code and gives them a green col
Type selectors are not case sensitive, so you can use both hl and HI to refer to the same heading,
The ID Selector
The ID selector is always prefixed by a hash symbol (#) and enables you to refer to a single
element in the page. Within an HTML or ASPX page, you can give an element a unique ID using the
id attribute. With the ID selector, you can change the behavior for that single element, like this:
#IntroText
font-style: italic;
The Class Selector
The Class selector enables you to style multiple HTML elements through the class attribute. This
is handy when you want to give the same type of formatting to a number of unrelated HTML elements.
The following rule changes the text to red and bold for all HTML elements that have their class
attributes set to Highlight:
Highlight
font-weight: bold;
color: Red;
Grouping and Combining Selectors
CSS also enables you to group multiple selectors by separating them with a comma. This is
handy if you want to apply the same styles to different clements. The following rule turns allheading
in the page to red:
h1, h2, h3, h4, h5, h6
color: Red;
4. yles, Themes and Master Pages
223
spe
Moreover, with Css you can also combine selectors, enabling you to hierarchically point tO a
cific element in a
page. You can do this by separating the selectors with a
space.
Types of CSS
There are the following three types of CSS:
Inline CSS
Internal CSs
2
3. External CSS
Inline CSS
For Inline CSS every style content is in HTML elements. It is used for a limited section.
Whenever our requirements are very small we can use inline CSS.
It will affect only single elements. In HTML we
require that various HTML tag's views are
different so then we use inline Cascading Style Sheets. There are
disadvantage of inline Cascading
Style Sheets. It must be specified on
every HTML tag. There is a lot of time consumed by that and it is
not the best practice for a good programmer and the code will be quite large and very complex.
Inline CSS examples are given below:
<!DOCTYPE html>
khtml xmlns="http://www.w3.org/1999/xhtml">
chead>
<title>Demo css</title>
</head
Kbody
<h3 style= "font-family:arial;background-color:green;" this is a test css </h3>
/body
/html
This
ent
class
C localhost:45741/HtmiPage1.html
Internal CSS
In internal CSS the style of CSS is specified in the <head> section. This is internal CSS, it affects
all the elements in the body section. Internal CSS is used in the condition when we want a style to be
USed in the complete HTML body. For that we can use style in the head tag.
This style performs an action in the entire HTML body.
is
ding
5. AdvancedWeb Programmir
224
!DOCTYPE html>
chtml xmlns=
" h t t p : / / w w w . w 3 . o r g / 1 9 9 9 / x h t m l " >
chead<title>Demo css</title>
style
body ffont-family:
'Buxton Sketch';
color : red;
b a c k g r o u n d - c o l o r
:yellow ;}
P color:blue;}
</style
</head>
cbody>
<h3 this is a test css </h3>
</body
</html>
C l o c a l h o s t : 4 5 7 4 1 / H t m I P a g e 1 . h t m l
this is a test 1ss
External CSS
In External CSS we create a .css file and use it in our HTML page as per our requirements
Generally external Cascading Style Sheets are used whenever we have many HTML attributes and we
can use them as required; there is no need to rewrite the CSS style again and again in a complete bode
of HTML that inherits the property of the CSS file. There are two ways to create a CSS file. The first
is to write the CSS code in Notepad and save it as a .css file, the second one is to directly add the style-
sheet in our Solution Explorer and direct Visual Studio to use it on our HTML page.
How to create and use an External CSS?
1. Right-click on your application name in Visual Studio 2012.
2. Add a style sheet.
3 Write your CSS code and save it.
4. Open your HTML page and drag down the style sheet.
5. Save and RUN.
<!DOCTYPE html>
chtml amlns="http://wwaw.w3.org/1999/xhtml">
chead
<title>Demo css</title>
<link href="aystyle.css" rel="stylesheet" />
</head>
cbody
<h3 this is a exaternal css </h3>
</body>
</html>
6. tyles,
Themes and Master Pages 225
C localhost:45741/HtmPage1.html
this is a eraternal css
CSS Example
ChangeCSSClass.aspx
w W w b s
bke Buld Deb Team Date mat he Tel Tet Windew he
X
. - Debug
Nin
Hello, TY BSc IT Students
ChangeCSsClass
Tesr wadboet aaY e
ChangeStyleon Click
Text wdut aqy
deduat ckus
Class Attached on Click
<%@Page Language="C#" AutoEventWireup="true" CodeFile="ChangeCSSClass.aspx.cs"
Inherits="ChangeCSSClass" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style
LabelGrey
font-weight:bold;
color.darkgray
LabelBlue
font-weight:norma;
color.darkblue;
ClassJoined
font-weightnormal;
font-size:50px;
7. dvanced Web Program
226
colordarkcyan;
s/style
titdle>c/title
</head»
<body
sform id="form 1" runat="server">
cdiv
<asp:Label ID="blMessage" runat="server" Font-Size="25px
Text"Hello, TY BSc IT Students" CssClass="LabelBlue"><lasp:Label><br,
<asp:Button ID="btnChangeCSS" runat="server" Text="Change CSS Class"
OnClick="btnChangeCSs_Click" Font-Bold="True" Font-Size="Medium">
<br/>
<br/>
<asp:Label ID="IblWithoutStyle" runat="server" Text="Text without any style" /><br /
<asp:Button ID="btnChangeStyle" runat="server" Text="Change Style on Click"
OnClick="btn ChangeStyle_Click" Font-Bold="True" Font-Size="Medium"
<br>
<br />
<asp:Label ID="IblWithoutClass" runat="server" Text="Text without any default class" /><br ib
<asp:Button ID="btnWithoutClass" runat="server" Text="Class Attached on Click"
OnClick="btnWithoutClass_Click" Font-Bold="True" Font-Size="Medium" >
</div>
</form>
</body
sIhtm
ChangeCSSClass.aspx.cs Code
using System;
using System.Web;
using System.Web.Ul;
using System.Web.Ul.WebControls;
public parialclass ChangecsSClass: System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
protected void btnChangeCSS_Click(object sender, EventArgs e)
8. Themesand MasterPages
st
227
b M E
nMessage.CssClass "LabelGrey":
prote
ed yoid btnChangeStyle_Click(object sender, EventArgs e)
IbIWithoutStyle.Text = "Text with Style":
WithoutStyle.Style.Add("font-size", "50px")
ntected void btnWithoutclass_Click(object sender, EventArgs e)
protec
IhIWithoutClass.Attributes.Add("class", "ClassJoined");
8.2Themes
Introduction to Themes
ASP.NET themes provide a centralized way to define the appearance of a Web site. Although
vour content pages can make use of themes, you can simply use master pages to set the theme for your
site as a whole. That is, you cannot use the Theme attribute within the Master directive at the top of
the master page (although you can still do so in the Page attribute of each of your content pages).
However, you can use your master page to provide a user interface element that allows the user to
browse and dynamically set the theme for your content pages.
You programmatically set the theme of a page within the Prelnit event of the page and you used
ASP.NET session state to store the currently selected theme. Unfortunately, you cannot set the theme
for your content pages within the Prelnit event of the master page. Instead, you must have the Prelnit
event handler within the content page. If you have hundreds or even thousands of content pages, does
that mean you must have the same Prelnit event handler in all of these content pages?
Fortunately, no; you can make use of some simple object-oriented inheritance so that you only
need code the Prelnit event handler once. Recall that the code-behind class for all Web Forms has the
Page class as its base class. You can define your own class that inherits from this base class and which
contains the Prelnit event handler that sets the themes. This new class then becomes the base class for
the code-behind classes in your site.
A theme is a collection of property settings that allow you to define the look of pages and
controls, and then apply the look consistently across pages in a Web application, across an entire Web
application, or across all Web applications on a server.
9. Advanced Web Prog
mming
228
Themes and Control Skins
and
other
resources. At a minimum, a theme will contain skins. Themes are defined in special directories
Web site or on your Web server.
Themes are made up of a set of elements: skins, Cascading Style Sheets (CSS), images
irectories
ar in your
Skins
such as Button, Label. TextBox, or
Calendarcontrols. Control skin settings are like the control marl..
itself, but contain only the properties you want to set as part of the theme. For example, the folloui
is a control skin for a Button control:
A skin file has the tile name extension .skin and contains property settings for individual cont
rkup
wing
asp:buttonrunat="server"
BackColor="lightblue"
ForeColor="black" />
You create .skin files in the Theme folder. A .skin file can contain one or more control skins f
one or more control types. You can define skins in a separate file for each control or define all th
skins for a theme in a single file.
the
There are two types of control skins, default skins and named skins:
A deault skin automatically applies to all controls ofthesame type when a theme is applied
to a page. A control skin is a default skin if it does not have a SkinlD attribute. For example
if you create a default skin for a Calendar control, the control skin applies to all
Calendarcontrols on pages that use the theme. (Default skins are matched exactly by control
type, so that a Button control skin applies to all Buttoncontrols, but not to LinkButton
controls or to controls that derive from the Button object.)
A named skin is a control skin with a SkinlD property set. Named skins do not
automatically apply to controls by type. Instead, you explicitly apply a named skin to a
control by setting the control's SkinlD property. Creating named skins allows you to set
different skins for different instances of the same control in an application.
Cascading Style Sheets
A theme can also include a cascading style sheet (.css file). When you put a .css file in the theme
folder, the style sheet is applied automatically as part of the theme. You define a style sheet using the
file name extension .css in the theme folder.
Theme Graphics and Other Resources
Themes can also include graphics and other resources, such as script files or sound files. For
example, part of your page theme might include a skin for a TreeView control.
As part of the theme, you can include the graphics used to represent the expand button and tne
collapse button.
Typically, the resource files for the theme are in the same folder as the skin files for that theme
but they can be elsewhere in the Web application, in a subfolder of the theme folder forexample. o
refer to a resource file in a subfolder of the theme folder, use a path like the one shown in this Image
control skin:
Sasp:Imagerunat="server" ImageUrl="ThemeSubfolder/filename.ext" >
You can also store your resource files outside the theme folder. If you use the tilde () syntax to
refer to the resource files, the Web application will automatically find the images. For example, if you
10. styles,
T h e m e s and
Master Pages
Tesources for a theme in a subfolder of your application, vou can use paths of the rorm
229
/ S u b F o l d e r / f
PhFolderlfilename.ext to refer to resource files, as in the following example.
2asp:Imagerunat="server" ImageUrl="JAppSubfolder/filename.ext" >
plac
Themes vs. Cascading Style Sheets
common attribut
following ways:
Themes are similar to cascading style sheets in that both themes and style sheets define a
set
utes that can be applied to any page. However, themesdiffer from style sheets in the
Themes can define many properties of a control or page, not just style properties. ro
example, using themes, you can specify the graphics for a TreeView control, the template
layout of a GridView control, and so on.
Themes can include graphics.
Themes do not cascade the way style sheets do. By default, any property values defined in a
theme referenced by a
page's Theme property override the property values declaratively set
on a control, unless you explicitly apply the theme using the StyleSheetTheme property. For
more information, see the Theme Settings Precedence section above.
Only one theme can be applied to each page. You cannot apply multiple themes to a page,
unlike style sheets where multiple style sheets can be applied.
How Themes Work
All themes are application specific.
In orderto use a Theme, create a folder that defines it.
This folder needs to be placed in a folder named App_Themes, which must be placed inside the top-
level directory for your web application.
For example, if application is called SuperCommerce and the theme is FunkyTheme, it should stay in
SuperCommercelApp_ThemeslFunkyTheme.
Only one theme can be active on a given page at a time.
Askin file is a text file with the .skin extension.
ASP.NET treats all the skin files in a theme directory as part of the same theme definition.
To apply the theme, set the Theme attribute ofthe Page directive to the folder name.
%@Page Language="C#"AutoEventWireup="true" ... Theme="FunkyTheme" %>
Scoping Themes
You can define themes for a single Web application, or as global themes that can be used by all
applications on a Web server. After a theme is defined, it can be placed on individual pages using the
neme orStyleSheetTheme attribute
ofthe
@Page directive, or it
can be
applied toallpages in an
application by setting the <pages> element in the application configuration file. If the <pages>
Cement is defined in the Machine.config file, the theme will apply to all pages in Web applications on
the server.
11. Advanced Web Programmina
230
Page Themes
A page theme is a theme folder with control skins, style sheets, graphics files and
created as a subfolder of the lApp_Themes folder in your Web site. Each theme is a diffe ther resout
ach theme is a
different
nt subfoli
page theme, defining two
thene
of the lApp_Themes folder. The following example shows a typical page theme, defininSubfola
named BlueTheme and PinkTheme.
MyWebSite
App_Themes
BlueTheme
Controls.skin
BlueTheme.css
PinkTheme
Controls.skin
PinkTheme.css
Global Themes
emes
A global theme is a theme that you can apply to all the Web sites on a server. Global the
the
allow you to define an overall look for your domain when you maintain multiple Web sites on t
same server.
Global themes are like page themes in that they include property settings, style sheet settings, ani
graphics. However, global themes are stored in a folder named Themes that is global to the Weh
server. Any Web site on the server, and any page in any Web site, can reference a global theme.
Applying a Simple Theme
In Visual Web Developer you can define page themes which you can then apply to one or mo
pages in your application. You can also create themes at the machine level that can be used in multiple
applications on the server.
Themes consist of several supporting files, including style sheets for page appearance, contrd
skins to define the appearance of server controls, and any other supporting images or files that make
up the theme. The content of a theme is the same whether the theme is defined as a page theme or asa
global theme.
Themes can be applied by using either the Theme or StyleSheetTheme attribute of the @Pag
directive, or by setting the pages Element (ASP.NET Settings Schema) element in the application
configuration file. Visual Web Developer will only visually represent themes applied by using the
StyleSheetTheme attribute.
To create a page theme
. In Solution Explorer, right-click the name of the Web site for which you want to create
page theme, and then click Add ASP.NET Folder.
2
2. Click Theme.
If the App_Themes folder does not already exist, Visual Web Developer creates it. VIsu
Web Developer then creates a. new folder for the theme as a child folder of tne
App_Themes folder.
12. and Master Page
yles, Themes
231
3. Type a name for the new folder.
The name of this folder is also the name of the pagc theme. For example, if you create a
folder named
App_l'hemesFirseTheme, the name of your theme is FirstTheme.
Add files to your new folder for control skins, style shects, and images that make up the
4
theme.
To add a skin file and a skin to a page theme
.In Solution Explorer, right-click the name of your theme and then click Add New Item.
. In the Add New Item dialog box, click Skin File.
3. In the Name box, type a name for the .skin file, and then click Add.
The typical convention is to create one .skin file per control, such as Button.skin or
Calendar.skin. However, you can create as many or as few .skin files as you neccd.
In the .skin file, add a normal control definition by using declarative syntax, but include only
4.
the properties that you want to set for the theme. The control definition must include the
runat"server" attribute, and it must not include the ID=" attribute.
The following code example shows a default control skin for a Button control, defining the
color and font for all of the Button controls in the theme.
<asp:Buttonrunat="server
BackColor="Red"
ForeColor"White"
Font-Name="Arial"
Font-Size="9px" />
This Button control skin does not contain a skinID attribute. It will be applied to all of the
Button controls in the themed application that do not specify the skinID attribute.
5. Repeat steps 2 and 3 for each control skin file that you want to create.
To add a cascading style sheet file to your page theme
1. In Solution Explorer, right-click the name of your theme and then click Add New Item.
2. In the Add New Item dialog box, click Style Sheet.
3. In the Name box, type a name for the .css file, and then click Add.
When the theme is applied to a page, ASP.NET adds a reference to the style sheet to the
head element of the page. For more information, see How to: Apply ASP.NET Themes.
Creating Global Themes
A global theme applies to all of the Web sites on a server. The location in which you create a
olderforglobal themes depends on whether you are running your Web site using Internet Information
SerVIces (IIS) or testing it using the ASP NET Development Server.
To create a
global theme
. Create a Themes folder using the following path.
2owindows%Microsoft.NETFrameworklversionASP.NETClientFilesThemes
SCreate a subfolderofthe Themes folder to hold your global theme files.
13. Advancod WebProgrammine
The name of the subfolder is the name ol the theme. For example, if you create
4.
232 you create a
folder
hat make up the
5. Add files to your
new folder for control skins, style shects, and images that make
global theme.
named
T h e m e s F i r s t T h e m e ,
the name ofyour
theme is FirstTheme.
If your
Web site is a file-system Web sile that you are lesting with the ASD
6.
7. If you are testing your Web site using a local IS Web Sile, open a command windou
run aspnet_regiis -c to install the theme on the server running IIS.
Development
Server, your theme is ready to test.
and
S. Ifyou are testing your thenme on a remote Web sile or an FTP Web sile, you must manu
ereate a Themes folder using the following path.
inually
I I S R o o t W e b l a s p n e t _ c l i e n t l s y s t e m _ w e b l v e r s i o n T h e m e s
level
s
applies styles and skins to all the pages and controls in the site unless you override a theme for
You can apply themes to a page, a Web site, orglobally. Setting a theme at the Web site leve
an
individual page. Setting a theme at the page level applies styles and skins to that page and all
By default, themes override local control settings. Alternatively, you can set a theme as a stvle
sheet theme, so that the theme applies only to control settings that are not explicitly set on the control
controls.
To apply a theme to a Web site
1. In the application's Web.config file, set the <pages> element to the name of the theme
either a global theme or a page theme, as shown in the following example:
2. <configuration>
3. <system.web>
4. pages theme-"ThemeName" >
5. /system.web>
6. Iconfiguration>
7. To set a theme as a style sheet theme and be subordinated to local control settings), set the
styleSheetTheme attribute instead:
8. configuration>
9 <system.web>
10. pages styleSheetTheme="Themename" >
11. /system.web>
12. <lconfiguration>
A theme setting in the Web.config file applies to all ASP.NET Web pages in that application.
Theme settings in the Web.config file follow normal configuration hierarchy conventions.
For example, to apply a theme to only a subset of pages, you can put the pages in a folder witn
their own Web.config file or create a slocation> element in the root Web.config file to specify a folder.
For details, see Configuring Specific Files and Subdirectories.
14. and Master Pages
233
Styles,Themesand
page
To apply a then to nn individual
Set the Thene
or stylesheetTheme attribute ofthe a@ Page directive to the name or c
theme to use, as shown in the following example:
o Page Theme="ThemeName"%
oPage StyleSheetTheme="ThemeName" %>
The theme and its corresponding styles and skins now applies only to the page declaring i.
Applying
Skins to Controls
Skins detined in your theme aPply to all control instances in the application or pages to which the
In some cases, you nmight want to apply a specific set ofpropertics to an individual
ene is applied.
tnalYou cando that by creating a named skin (an cntry in a .skin ile that has a SkinlD property
set) andthen pplying it by ID to individual controls.
To apply a named skin to a control:
Set the control's SkinlD property, as shown in the following example:
<asp:Calendarrunat="server" ID="DatePicker" SkiniD="SmallCalendar" >
If the page theme does not include a control skin that matches the SkinID property, the
control uses the default skin for that control type.
Handling
Theme Conflicts
When properties conflict between your controls and yourtheme, the theme wins.
To make this change, just use the StyleSheetTheme attribute instead of the Theme attribute.
<%@PageLanguage=C#"AutoEventWireup="true" . . . StyleSheetTheme="FunkyTheme" %>
8.3Master Page Basics
ASP.NET master pages allow you to create a consistent layout for the pages in your application.
A single master page defines the look and feel and standard behavior that you want for all of the pages
(or a group of pages) in your application. You can then create individual content pages that contain the
content youwantto display. When users request the content pages, they merge with the
master page to
produce output that combines the layout of the master page with the content from the content page.
Advantages of Master Pages
Master pages provide functionality that developers have traditionally created by copying existing
code, text, and control elements repeatedly; using framesets; using include files for common elements;
using ASP.NET user controls; and so on. Advantages of master pages include the following:
They allow you to centralize the common functionality of your pages so that you can make
updates in just one place.
They make it easy to create one set of controls and code and apply the results to a set of
pages. For example, you can use controls on the master page to create a menu that applies to
all pages.
They give you fine-grained control over the layout of the final page by allowing you to
control how the placeholder controls are rendered.
15. Advanced Web Programmins
234
They provide an object model that allows you to customize the master page from individ
content pages.
Master pages actually consist of two pieces, the master page itself and one or more content nao
Master Pages
vage
A master page is an ASP.NET file with the extension .master (for example, Mysite.master) wi
with
for
a predefined layout that can include static text, HTML elements, and server controls. The master na
is identified by a special @ Master directive that replaces the @ Page directive that is used
ordinary .aspx pages. The directive looks like the following.
C#
%Master Language="C#" %>
can
contain. For example, the following master-page directive includes the name of a code-behind file. and
assigns a class name to the master page.
The @ Master directive can contain most of the same directives that a Control directive
C#
<%@ Master Language="C#"Code File="MasterPage.master.cs" Inherits="MasterPage" %>
In addition to the@Master directive, the master page also contains all of the top-level HTML
elements for a page, such as html, head, and form. For example, on a master page you might use an
HTML table for the layout, an img clement for your company logo, static text for the copyright notice,
and server controls to create standard navigation for your site. You can use any HTML and any
ASP.NET elements as part of your master page.
Content Pages
You define the content for the master page's placeholder controls by creating individual content
pages, which are ASPNET pages (.aspx files and, optionally, code-behind files) that are bound to a
specific master page. The binding is established in the content page's @ Page directive by including a
MasterPageFile attribute that points to the master page to be used. For example, a content page might
have the following @ Pagedirective, which binds it to the Master1.master page.
C# code
%@Page Language="C#"MasterPageFile="-IMasterPages/Master1.master" Title="Content
Page%
In the content page, you create the content by adding Content controls and mapping them to
ContentPlaceHolder controls on the master page. For example, the master page might have content
placeholders called Main and Footer. In the content page, you can create two Content controls, one
that is
mapped to the ContentPlaceHolder control Main and the other mapped to the
ContentPlaceHolder control Footer, as shown in the following figure.
16. Pages
styles, Themes
and Master
235
Replacing Placeholder Content
eMaster file "A.master"
<%Master%> Content file "A.aspx"
<6PageMasterPageFile=
"A.master" %>
<asp:contentplaceholder
runat-server id="Main /»
asp:Content runat=server
ContentPlaceHolderId="Main'
Content here</asp:Content>
runat=server 1d="Footer" / <asp:Content runat=server
sasp:contentplaceholder
ContentPlaceHalderId="Footer"
Content here</asp:Content>
Resulting
Page
After creating Content controls, you add text and controls to them. In a content page, anything
that is not inside the Content controls (except script blocks for server code) results in an error. You can
Derform any tasks in a content page that you do in an ASP.NET page. For example, you can generate
content for a Content control using server controls and database queries or other dynamic mechanisms.
Acontent page might look like the following.
[C#]
<%@PageLanguage="C#" MasterPageFile="-/Master.master" Tile="Content Page 1" %>
<asp:Content ID="Content1" ContentPlaceHolderiD="Main" Runat="Server">
Main content.
slasp:Conternt>
sasp:Content ID="Content2" ContentPlaceHolderiD="Footer" Runat="Server">
Footer content.
/asp:content>
The @ Page directive binds the content page to a specific master page, and it defines a title for
the page that will be merged into the master page. Note that the content page contains no other markup
outside of the Content controls. (The master page must contain a head element with the attribute
runat="server" so that the title setting can be merged at run time.)
You can create multiple master pages to define different layouts for different parts of your site,
and a different set ofcontent pages for each master page.
Run-time Behavior of Master Pages
At run time, master pages are handled in the following sequence:
. Users request a page by typing the URL of the content page.
When the page is fetched, the @ Page directive is read. If the directive references a master
page, the master page is read as well. If this is the first time the pages have been requested,
both pages are compiled.
2.
17. Advanced Web Progfam
3The
master page
with the updaled
content s merged
into the control
3.
236 ed into the control tree
the conten
The
content
of
individual
Content
controls
4
is merged into the correspona
5. The resultingmergedpage is
rendered to the
browser.
The process
is
illustrated in the following
diagram.
Content
PlacecHolder
control in the master page.
Master Pages at Run Time
Content file "A.aspx"
Master file "A.master"
<%Master%>
Y%@Page MasterPageFile=
"A.master" %>
asp: contentplacehol der
funat server 1da"Mafn" /
«35p:
Content runat server
Content PlaceHolderId="MaIn
Content here</asp:Content>
a s p : c o n t e n t p l a c e h o l d e r
runat-server 1d='Footer" >
«asp:Content runat=server
ContentPlacelol de rId=" Footer"
Content here</asp:Content»
Resulting
Page
From the user's perspective, the combined master and content pages are a single, discrete nas.
The URL of the page is that of the content page.
page
From a programming perspective, the two pages act as separate containers for their respecti
controls. The content page acts as a container for the master page. However, you can reference puki
master-page members from code in the content page, as described in the next section.
Note that the master page becomes a part of the content page. In effect, the master page acts
much the same way a user control acts as a child of the content page and as a container within the
page. In this case, however, the master page is the container for all of the server controls that
rendered to the browser. The control tree for a merged master and content page looks somethingli
this:
Page
Master Page
(Master page markup and controls)
ContentPlaceHolder
Content page markup and server controls
(Master page markup and controls)
ContentPlaceHoider
Content page markup and server controls
(Master page markup and controls)
18. Styles,ThemesandMaster Pages
Scoping aster Pagees
237
CAn attach content pages to a master page at three levels:
At the page level Y Ou can use a
page directive in each content page to bind it to a
mas
page, as in the
following code example.
C#
%@Page Language="C#"MasterPageFile="MySite.Master" %>
At the application level By making a
setting in the pages element of the
application
configuration file
(Web.config), you can specify that all ASP.NET pages (.aspx files) in the
application automatically bind to a master page. The element might look like the following
<pages masterPageFile="MySite.Master" >
If you use this strategy, all ASP.NET pages in the application that have Content controls are
merged with the
Specified master page. (If an ASP.NET page does not contain Content
controls, the master page is not
applied.)
At the folder level This strategy is like binding at the application level, except that
you
make the setting in a
Web.config file in one folder only. The master-page bindings then
apply to the ASP.NET pages in that folder.
Connecting Master Pages and Content Pages
Creating a Master Page
Creating a master page is very simple. In your website, right click on Solution Explorer, select
Add New Item, and then select the Master Page from the pop up window, as shown in the figure. The
Master Page comes with the extension .master which consists of all the common elements (a
template/layout) for the site.
AddNiew item E:ProjectslThemeManagerk
InstaledTemplotes Sart by: Defat
rtai-i Tercidas P
Vaud Bez
Web Form
Type: Ysual C
Viss C
AMaste Page for web Applczors
Cnine Tercltes
Mater Page Veud Ca
WebUser Cortrd Ysua Ct
AJAX-enabled WCF Service Vaua
lC
Broser Fie Veud Ce
Clees vue Ca
ess Deyom Voud Co
Dotst Viuod C
Viual C&
77DmaricDotaField
Generic Hander Visual C
Gdbal Aprcabion Class Yeul Cs
HTML Page Vsual Co
Place codein separate file
select masterpage
MaerPoge2.maner
Add Cancel
19. Advanced Web
Programm
238
d in it. The code for
By default the Master Page comes with two content place holders placed in it T
Master Page is as follows:
%@Master Language="C#"AutoEventWireup="true"CodeFile="MasterPage.master eon
Inhents="MasterPage"%>
In the above, theMasterdirective identifies it as a master page, whercas all othee
an@pagedirective.
her pages ha
htmkmins="http://www.w3.org/1999/xhtml">
headrunat="server>
stite>title
asp:ContentPlaceHolder id="head"runat="'server">
asp:ContentPlaceHolder>
<head
body
sfom id=fom1"runat="server>
div>
asp:ContentPlaceHolder id="content"runat="server">
asp:ContentPlaceHolder>
ldiv
<fom>
s/body
<html>
The content place holders in the above are used to place static content or dynamic content b
using ASP.NET server controls in the site. The content place holder is placed in the header section and
in the formm tags which in general allows users to place page content in the header and body part, but
there is no such restriction to place a content placeholder under a particular tag nor is there any
restriction on the number of content placeholders to be used. In the latter part of the article, we willsee
in detail about the layout and usage ofthe content placeholder.
Content placeholders allow the user to flexibly maintain site content with a common page layout
Adding a Content Placeholder
We have now created a Master Page, we now need to add a content placeholder to the site. Right
click on Solution Explorer, select Add New Item, and select a content place holder from the pop up
window
20. 239
s t y l e s ,
Themes
and Master Pages
ANew lem
E:ProjectsThemoManager
Sort by Dela
InstelledTempletes
ViaalResk
Web Fem
MiualC
Vsul C
Type VudC
Aform lor Web Apohetiors
O n n e e n p l s ' e s
Master Page VualC
Web User Contro VieualC
AJAWonabledWCF Sorvica Visud C
Browsor Flo ViuolCe
Class Visual Ce
Clss Diagram Visual C
DSet Visual Ce
Dymamlc Data Field Vsuol C
Genertc Hander Vsual Cs
Gbbal Applikatlon Class Vsual C
HTML Page
vsual Ct
Hececosepuratefile
Select master page
Defaut2.aspx
Name
Add Cancd
This adds the content place holder to the site with the following code incuded in the page:
Hide Copy Code
c%@Page Title="" Language="C#"MasterPageFile="-/MasterPage.master"
AutoEventWireup="true"CodeFile="Default2.aspx.cs" Inherits="Default2"%>
< a s p : C o n t e n t I D = " C o n t e n t i " C o n t e n t P l a c e H o l d e r i
D = " C o n t e n t P l a c e H o l d e r 1 " R u n a t = " S e r v e r >
asp:Content
Creating a Nested Master Page
In order to create a nested master page,
follow the below steps. Repeat the above steps to add a
Master Page and then right click on Solution Explorer and select Add New Item and select Master
Page from the installed templates and then select the 'Select Master Page' checkbox and name the
master page
nestedmaster.master, as shown in the below figure.
21. Advanced Web Programn
240
Add Newlem ProjectsMasterPages
tes Sort by Defe
Iyp VmdC
Vmud C
web Forn AMar Pge for web Aqpe s
Wsu C
oriee Tens Maste Page
u C
Web User Cortrd
suel C
AMXenabled w Servk
Wsu C
Browwe Fi
isul Ca
Jass
Vsual Ca
Jas Olngram
sualC
sualC
Dynami Data Field
Cenerc Hander hsual C
Vsuel Ca
Gcbal Appkcabon Closs
Visualc
HTM Page
Place codeinseparatefie
5electmaster page
iestedMestermaster
Add Carcel
From the below code, we can observe the differences in the code for a master page, content page
and nested master page.
Master Page
<%@Master Language="C#"AutoEventWireup="true"CodeFile="MasterPage.master.cs"
Inherits="MasterPage"%
Nested Master Page
<%@MasterLanguage="C#"MasterPageFile="-/MasterPage.master
AutoEventWireup="true"CodeFile="NestedMaster.master.cs" Inherits="NestedMaster%>
Content Page
%@Page Title=" Language="C#"MasterPageFlle="-/MasterPage.master"
AutoEventWireup="true"'CodeFile="Default2.aspx.cs" Inherits="Defauli2"%>
By this, we have created a nested master page for the site. Now we need to design the c
chili
master page.
<asp:ContentID="Content1'ContentPlaceHolderlD="ContentPlaceHolder1"Runat="Server">
<div
<h1 Image Slide Show</h1>
<h3>Product's Show Case:</h3>
sasp:ImageID="Image1"runat="serverlmageUr="-/Blue hills.jpg" Height="173px
22. Master Pages
tyles, Themes and
241
Width="287px"/>
<asp:C
.contentPlaceHolder ID=ContentPlaceHolder1"runat="server"r>
<lasp:ContentPlaceHolder>
/div>
s / a s p : C o n t e n t >
8.4Advanced Master Pages
Replaceable Content Placeholders
In addition to statictext and controls that will appear on all pages, the master page also includes
ane or more ContentPlaceHolder controls. These placeholder controls define regions where
enlaceable content will appear. In turn, the replaceable content is defined in content pages. After you
repla
have defined the ContentPlaceHolder controls, a master page might look like the following.
C#
%@Master Language="C#" 9%>
IDOCTYPE html PUBLIC "-//W3CIIDTD XHTML
1.1/EN" "http://www.w3.org/TR/xhtmi11/DTD/xhtm1 1.dtd"
<html xmlns="http://www.w3.org/1999/xhtml'>
<head runat="server">
stide>Master page title</title>
</head
<body
<formid="form1"runat="server">
stable>
<tr
std>asp:contentplaceholder id="Main"runat="server" /></td>
<td<asp:contentplaceholder id="Footer"runat="server" (></td>
</t
</table>
</form>
<body
</html>
Master Pages and Relative Paths
In all the examples we've seen thus far, the master and content pages have been located in the
Same folder (the website's root folder). But there's no reason why the master and content pages must
Dc In the same folder. You can certainly create content pages in subfolders. Similarly, you might
eale a-/MasterPages/ folder where you place your site's master pages.
23. Advanced Web Programmi
ning
242
One potential issue with placing master and content pages in different folders involves bro
URLs. If the master page contains relative URLs in hyperlinks, images, or other elements, the link wi
be invalid for content pages that reside in a different folder.
sken
Rather than hard code an absolute URL, ASP.NET allows page developers to use the tilde ()s
indicate the root of the web application. For example, we can use the notation JAdmin/Default.asr
in the text to refer to the Default.aspx page in the Admin folder. The indicates that the Admi
folder is a subfolder of the web application's root.
Aspx
Master pages very often include links, images, and other external resources that must be specified
1a a URL. Because the master page and content pages might not exist in the same folder, it i
important to abstain from using relative URL. While it is possible to use hard coded absolute URI
doing so tightly couples the absolute URL to the web application. Ifthe absolute URL changes -
as
otten does when moving or deploying a web application you'l have to remember to go back and
update the absolute URLs.
The ideal approach is to use the tilde () to indicate the application root. ASP.NET Web controls
that contain URL-related properties map the ~ to the application root at runtime. Internally, the Weh
controls use the Control class's ResolveClientUrl method to generate a valid relative URL. This
method is public and available from every server control (including the Page class), so you can use it
programmatically from your code-behind classes, if needed.
8.5Questions
1. What are themes? What is the use of themes in asp.net website?
What is the difference between themes and CSS?
2
Explain types of CSSS.
Explain CSS selectors.
3.
What is Master Page? Explain relation between content page and master page.
5.
What are the advantages of a master page? Explain about ContentPlaceHolder"s in master pages.
What is the use of Master Pages in ASP.NET? How a Content page can be added to a Master Page.
6.
S. Write a short note on Nested Master Pages.
What is the significance of Master pages in ASP.NET? What is the name given to pages other than
mastær pages? Explain in detail.
9. What is the relationship berween master page and content page?
9.
10.