You are on page 1of 83

ViewState

• The ViewState is a state management technique in ASP.NET.

• It helps regular page member variables to maintain their values across

postbacks.  ( That is the form is not automatically cleared across

postbacks.)

• Viewstate mechanism automatically store values between multiple

requests for the same page.

• Viewstate is rendered to the browser as a hidden variable _viewstate.

• Viewstate value is accessible only at page level.


Enabling and Disabling ViewState
• The EnableViewState property is used to set ViewState of a page or a
specific controls.
• It is set to true for all server controls by default.

• The ViewState property can be enabled or disabled at page level as follows:

<%@ Page Language="C#" EnableViewState=“true | false” %>

• The ViewState property of a specific control can be enabled or disabled as


follows:
<asp:Label EnableViewState="false" ID="Label1" runat="server"
Text="Label1"></asp:Label>
viewstate.aspx
.
.
.
<asp:TextBox ID="TextBox1" runat="server" Text="TextBox1"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button1"
onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label1" />
<br /> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Button2"
onclick="Button2_Click" />
<asp:Label ID="Label2" runat="server"></asp:Label>
.
.
.
viewstate.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) { }
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = TextBox1.Text;
}
protected void Button2_Click(object sender, EventArgs e)
{
Label2.Text = TextBox2.Text;
}
}
ViewState and Page_Load
• Page_Load() event happens after the ViewState is established
its previous value.
• So if you want to set some values in the page load event as
values for initial request, that should not be in the post back or
subsequent requests.
Performance and Security considerations for
ViewState
• The view state feature of ASP.NET can impact web pages dramatically, not
only be in page size but also in server side performance. 
• It is advisable to use view state, if you want to store a small amount of data
for a page that will post back to itself.
• If your view state data is large, the application will be slow.

• This is because the contents of _viewstate must be included in the HTTP


post back request.
• To ensure that the view state remains secure you can adopt one of the
following measures:
– Use the EnableViewStateMac property.
– Encrypt the view state content.
Cookies

• A cookie is a technique used for client side state management.

• It helps Web applications to store user-specific information. 

• It is a text file stored on the client side by the browser.

• These files store name value pairs.

• A Web application can read the information stored on the cookie

whenever the user visits the site.


Types of Cookies
• Cookies are of two types
– Temporary (Transient or session) cookies

It is alive in the main memory as long as the users session is


alive.
– Permanent cookies

It is stored on the client disc and its expiration date


determines how long the cookie remains on the client’s
computer.
HttpCookie, HttpRequest & HttpResponse
• HttpCookie is a class present System.web namespace.
• This namespace also contains classes such as HttpRequest and
HttpResponse classes.
• Response object represents a valid HttpResponse that was
received from the server.
• Request object represents a valid HttpRequest before it has been
sent to the server.
HttpCookie
• A cookie can be created using the following constructors of
HttpCookie class.
– HttpCookie(String) // Creates and names a new cookie.
– HttpCookie(String, String) //Creates, names, and assigns a
value to a new cookie.

• Properties
– Name ---- Gets or sets the name of a cookie.
– Value ---- Gets or sets an individual cookie value.
– Expires ---- Gets or sets the expiration date and time for the
cookie.
HttpCookieCollection
• The HttpCookieCollection class contains cookies that were

previously written to the client.

• AllKeys property of this class gets a string array containing all

the keys (cookie names) in the cookie

• Count property of this class gets the number of key/value

pairs.

• Its Add method adds a cookie into the collection.


Creating and Reading Cookies using
Request and Response Objects.
• Cookies property of Response and Request objects are used to
manipulate HttpCookieCollection object.
• Syntax for Creating a Cookie:
Response.Cookies[“cookie name”].Value=“specify value”;
Example:-
Response.Cookies["uname"].Value = TextBox1.Text;
• Syntax for Reading a Cookie:
String str=Request.Cookies[“cookie name”].Vaue;
Example:-
string str= Request.Cookies["pwd"].Value;
Creating and Deleting a Persistent Cookie.
HttpCookie h1 = new HttpCookie("Username", "vista");
h1.Expires=DateTime.Now.AddDays(2);

h1.Expires=DateTime.Now.AddDays(-2); //deletes
HttpCookieCollection Example
using System; using System.Web;
public partial class _Default : System.Web.UI.Page
{ protected void Page_Load(object sender, EventArgs e) { }
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie h1 = new HttpCookie("Username", "vista");
HttpCookie h2 = new HttpCookie("Password", "symphony");
h1.Expires=DateTime.Now.AddDays(2);
h2.Expires=DateTime.Now.AddDays(2);
HttpCookieCollection c = Response.Cookies; c.Add(h1); c.Add(h2);
}
protected void Button2_Click(object sender, EventArgs e) {
HttpCookieCollection c = Request.Cookies;
string[] s = c.AllKeys;
for (int i = 0; i < s.Length; i++)
{
HttpCookie hc = Request.Cookies[i];
Label1.Text += "<br/>" + hc.Name +":"+ hc.Value + "<br/>";
}
} }
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<html ><head runat="server"><title></title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label2" runat="server" Text="Enter User Name"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox> <br />
<asp:Label ID="Label3" runat="server" Text="Enter Password"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password" >
</asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click“ Text="Set" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click“ Text="Get" />
<br /> <asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form> </body>
</html>
Default.aspx.cs
using System;
using System.Web;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Cookies["uname"].Value = TextBox1.Text;
Response.Cookies["pwd"].Value = TextBox2.Text;
Response.Cookies["uname"].Expires = DateTime.Now.AddDays(2);
Response.Cookies["pwd"].Expires = DateTime.Now.AddDays(2);
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "<br/>" + Request.Cookies["uname"].Value + ":" +
Request.Cookies["pwd"].Value+ "<br/>";
}
}
Advantages and Drawback of Cookies
• Advantages
– Cookies are very easy to create and manipulate.
– Cookies do not require any server resources since
they are stored on the client. 
• Drawbacks
– Users can edit or delete cookie files. 
– Cookies stores data in text files and hence not
reliable in storing sensitive data.
– Can store only small amount of data.
Session State
• HTTP is a stateless protocol.

• So each HTTP request for a page is treated as an independent request.

• The server retains no knowledge of variable values that were used

during previous requests.

• Session state identifies requests from the same browser during a

limited time window as a session, and provides a way to persist

variable values for the duration of that session.

• It is a server-side state management technique.


Session ID
• A user session is identified with a unique session id.

• This session id is used to get the session state object.


Adding/Updating Session Variables
• Session[" session_variable_name"]=value;

Example:-

Session["FirstName"] = t1.Text;
Session["LastName"] = t2.Text;

• The session variable can also be added using add() method.

Example:-

string s1 = TextBox1.Text;
Session.Add(“itm1”, s1);
Retrieving Session Variables

• String variable=Session[“session_variable_name”].ToString();

Example:-
string x = Session["itm1"].ToString();
Application State

• Session State stores data for single user session.

• So Session State variables are like single user global variable.

• Application State stores data shared by all users of an application.

• So Application State variables are like multi user global variable.

• Application State variables are stored on the web server.

• It is a server-side state management technique.


Application State
• Application state variables are available as long as application
is running.
• The session state variables are cleared whenever the time out
of that session is reached whereas application state variables
are cleared only when the process hosting the application is
restarted.
• Following is the syntax for creating application state variable:

Application[“name variable”]=“value”;
Example
using System; using System.Collections.Generic;
using System.Linq; using System.Web;
using System.Web.UI; using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
int count=0;
protected void Page_Load(object sender, EventArgs e) {
count = Convert.ToInt32(Application["counter"]);
count++;
Label1.Text = "<b>This site is visited " + count+ " times </b> ";
}
protected void Page_PreRender(object sender, EventArgs e)
{
Application["counter"] = count;
}
}
URL Encoding
• Another way of maintaining state information is by using URL encoding.

• The state information is stored in a Query String.

• This Query String is appended to the end of a page URL.

• Query Strings are used in hyperlinks, anchor elements, Respone.Redirect,

Response.RedirectPermanent , Server.Transfer or PostBackURL property

of a Button control to pass information from one page to another.


URL Encoding Syntax
• The first attribute is specified with a question mark followed
by the attribute name, equal to sign and the attribute value.
• The subsequent attributes are specified with ampersand (&)
symbol.
• Following is an example of a URL with a single Query String.

Default2.aspx?Name=Raj
• Following is an example of a URL with three Query Strings.

Default2.aspx?Name=Raj&address=konat place&city=delhi
Retrieving the value of a Query String
• To retrieve the value of a Query String attribute, use the
QueryString property of the HttpRequest object and specify
the attribute name.
• Request.QueryString["Attribute_Name"];

• Following statements retrieve the values of the Query String


attributes.
Label1.Text = "Name: "+Request.QueryString["Name"];
Label2.Text = "Address: " + Request.QueryString["address"];
Label3.Text = "City: "+Request.QueryString["city"];
Example (default1.aspx.cs)
protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("Default2.aspx?Name=Raj&address=Ashok
Road&city=delhi");
}

Or

protected void Button1_Click(object sender, EventArgs e)


{
Server.Transfer("Default2.aspx?Name=" + TextBox1.Text +
"&address=" + TextBox2.Text + "&city="+TextBox3.Text);
}
Cntd. to next slide
Example (default2.aspx.cs)
.
.
.

protected void Page_Load(object sender, EventArgs e)


{
Label1.Text = "Name: "+Request.QueryString["Name"];
Label2.Text = "Address: " + Request.QueryString["address"];
Label3.Text = "City: "+Request.QueryString["city"];
}

.
.
.
Introduction to Cascading Style Sheets
• Stylesheets are used to control how elements are presented in
the Web page. 
• A style sheet consists of a list of rules that affect the appearance
of one or more documents.
• It gives a uniform look and feel for your web application.

• Style sheets make it easy to specify the color and font of text,
the margin between various elements on a webpage, and a host
of other details.
Need of CSS
• It helps you to separate the style information from the content on
your web page.
• This approach has the following advantages:
– It avoids redundancy. 
– It ensures easy maintenance.
The look and feel of the web site can be changed simply by
altering CSS file; in contrast use of HTML formatting
elements would require every file to be updated to change the
appearance.
• Style sheets are useful because you can use the same style sheet
for many documents. 
Basic Structure of a Style
• A style sheet consists of a set of rules.
• Each rule has the following syntax.
Syntax:-
selector { property:value; }

Example:-
P { font-family: "ARIAL“; }

Note:-
The property is followed by a colon (:) and the value is
followed by a semicolon(;)
CSS Comment
• A comment line can be included in a stylesheet as follows.

/* Comment here */
Types of Selectors
Following are the common type of selectors.
• HTML Tag Selectors
• Class Selector
• ID Selector
• Grouped Selector
• Context Selector
HTML Tag Selectors
• It is used to set the style of a specific tag.
Syntax:-
selector { property:value }

• Example:-
body { font-family: ARIAL; font-size: 1em; color: aqua; }
h3 { color:aqua; }
Class Selectors
• It styles all elements with the specified class.
• It starts with a period(.) symbol.
Syntax:-
.classname { property:value; }
• Example:-
.test { font-family: ARIAL; font-size: 1em; color: aqua; }
• A class can be applied to selected HTML elements as follows.
h1.test{ color:silver;font-size:2em; }
Here the style ‘test’ is applicable only to h1 tag.
so <p class= "test">STYLE NOT APPLIED</p>
<H1 class="test"> STYLE APPLIED </H1>
ID Selectors
• The id selector is used to specify a style for a single, unique
element.
• It is defined with a “#” symbol at the beginning.

Syntax:-
#selector { property:value; }

• Example:-
#abc { color:navy; font-family: "ARIAL; font-size: 1em; }
Grouped Selectors
• If there are multiple elements with the same style then these
elements can be grouped and a common style definition can be
made for the group.
• Separate each element in the group with a comma.
• Example:-
h1,h2,h3, p
{
color:lime;
}
This is equivalent to:
h1{color:lime}
h2{color:lime}
h3{color:lime}
b {color:lime}
Grouped Selectors
• If there are multiple elements with the same style then these
elements can be grouped and a common style definition can be
made for the group.
• Separate each element in the group with a comma.
• Example:1-
h1,h2,h3, p h1{color:lime}
{ h2{color:lime}
color:lime; This is equivalent
h3{color:lime}
} to:
b {color:lime}
• Example:2-
h2,P.TES
{
color:teal;font-size:2em
}
Context Selectors
• These are selectors which work only in certain contexts.
• Syntax:
Tag1 Tag2 { ... }
Here the style will be applied to the Tag2 only when it is within
the Tag1, as it is shown below.
<Tag1>
<Tag2> ... </Tag2>
</Tag1>
• Example:-
PB {
font-weight: bold; color:Navy
}
• The above style is applied only when <p> and <b> tags come
together as: <p><b>Context Selectors</b></p>
Type of CSS
Following are the types of CSS:
• Inline Styles
• Internal (Embedded) Styles

• External styles
Inline Styles
• Inline Styles are placed directly inside the HTML element in the
code.
• Style applies to the tag in which it is defined.
• This kind of styles are useful when you want apply style to an
individual element in an HTML document.
• Style is defined within an HTML element and hence can be
reused.
<body>
<h1 style=“Style definition goes here”>Applied Only to this text </h1>
</body>
Inline Style Example
<html>
<body style=" background:silver; color:Navy;font-size:2em" >
<h1 style="color:Olive" >Inline Style Sheet Example</h1>
</body>
</html>
Internal (Embedded) Styles
• Style declaration is in the head of the page.
• It can be used only for the web page in which it is defined.
• So embedded styles are not reusable for other pages.

<head>
<style type="text/css">
Style definition goes here
</style>
</head>
<body>
</body>
Internal Style Example
<html>
<head>
<style type="text/css">
body { background:silver}
h1,p { color:Navy;font-size:2em }
</style>
</head>
<body>
<h1><u>Internal Style Sheet Example</h1></u>
<p>Style declaration is in the head of the page.</p>
<p>It can be used only for the web page in which it is defined.</p>
<p>So embedded styles are not reusable for other pages.</p>
</body>
</html>
External Style Sheets
• External style sheets consists of a list of rules that can be applied
to one or more web pages.
• It helps you to separate the style information from the HTML file.
• The styles are external to, or outside of, the web page.

• External style sheets can be linked to any number of web pages


and thereby providing maximum reusability.
• External style sheet files have extension .css
• An external style sheet can be linked to a web page using link tag
as follows:

<link rel=“stylesheet” href=“Styles/Sstl.css” type=“text/css” >


External Style Sheet Example
.test { color:lime }
h2,p.tes { color:teal;font-size:2em }
h1.tes { color:silver;font-size:2em }
h1 {color:red}
h2 {color:navy}
h3 {color:green}
h4,h5 {color:aqua}
p {color:fuchsia; font-family:"times"}
#abc { color:yellow; font-family: "arial; font-size: 1em}
#nnn { color:red; font-family: "arial; font-size: 3em}
p b { font-family: times, serif; font-weight: bold; color:navy }
External Style Example
<%@page language="c#" %>
<html><head>
<link href="styles/tim.css" rel="stylesheet" type="text/css" />
</head> <body>
<p class="tes">Class Selector for Paragraph</p>
<h1 class="tes"> Class Selector for H1 </h1>
<h1>This text is printed in red color</h1>
<h2>This text is printed in navy blue color</h2>
<h3>This text is printed in green color</h3>
<h4>This text is printed in aqua color</h4>
<h5>This text is printed in aqua color</h5>
<h1 id="abc"> ID Selector for h1</h1>
<h1 id="nnn"> ID Selector for h1</h1>
<p><b>Grouped selector</b></p>
</body>
Length Units
• A length value is formed by an optional + or -
• Relative (relative to another length) units
em (equal to the height of the element's font)
ex (equal to the height of the lowercase letters such as "x")
px (in pixels, relative to the canvas resolution)
• Absolute units
in (inches; 1in=2.54cm)
cm (centimeters; 1cm=10mm)
mm (millimeters)
pt (points; 1pt=1/72in)
pc (picas; 1pc=12pt)
• Note:-
Spaces are not allowed in a length value; e.g., 2.5 cm is not a
valid length value, but 2.5cm is valid.
URL -Uniform Resource Locator
• A URL value has the form: URL(url goes here)
• The URL may be optionally quoted with either single or double
quotes.
• Examples:
body{background-image:url("logo.jpg") }
body{background-
image:url("http://www.tineye.com/images/widgets/
mona.jpg")}
Font Properties
Property Description
font-style The values for the font style are:
• Normal-normal style
• Italic-Italic style
• Oblique- similar to italic
• Inherit-style will be inherited from parent element.
font-weight The values for the font weight are: Normal, Bold, Bolder,
Lighter, etc.
font-size Specifies the size of the font.
The values for the font are: small, medium, large, x-small,
xx-small, x-large, xx-large, length in px, cm,% etc.
font-family p{font-family:"Times New Roman", Times, serif;}
Text Properties
Property Description

Text-transform The text-transform property controls the capitalization of


text. The values for the Text-transform are:
• None- The text renders as it is.
• Capitalize-converts first letter of each word to uppercase.
• Uppercase- converts to uppercase
• Lowercase-converts to lowercase
• Inherit- inherits from parent element.

Text-decoration The values for the Text-decoration property are:


None, underline, overline, line-through, blink.

Text-align The values for the Text-decoration property are:


Left, right, center, justify

Text-indent Text-indent:10%, 1.5px,


Color Properties
Property Description
color Defines text color.
The color value can be one of the following:

• Predefined names:
White, black, red …
• 8-bit hexadecimal intensities for red, green, blue:
#ff0000
R G B
• 0-255 decimal intensities:
rgb(255,255,0)

R G B
• Percentage intensities:
rgb(80%,80%,100%)
R G B
Background Properties
Property Description
Background-color Defines background color. The color value can be hexadecimal
or any valid color constant.
background-color:#ffffff
background-color:ff0000
background-color:red
background-color:rgb(255,255,0)
Background-image Values: none or url
body{background-image:url("logo.jpg"}
body{background-image:url("http://www.tineye.com
/images/widgets/mona.jpg")}
Background-repeat Values: Repeat, repeat-x, repeat-y, no-repeat
Background-attachment Values: Scroll, fixed
Border Properties
Property Description

Border-style Values: none, hidden, dotted , dashed, solid, double,


groove, ridge, inset, outset, inherit.

Border-color Defines border color. The color value can be hexadecimal


or any valid color constant.

Border-width Values: thin, medium, thick, or width in px, cm, etc.

Setting unique The directions are top, bottom, left and right. Using this
Border to each property one can set unique border for each side of an
direction html element.
Border-bottom-style:double
Border-top-style:single
Border-left-style:none
Border-right-style:none
Margin Properties
Property Description
Margin Specifies the margin of the html element.
The value can be in px, cm,% etc.
Eg:margin:2Px means a uniform margin of 2Px on all sides.
Setting unique The directions are top, bottom, left and right. Using this property
margin to each one can set unique border for each side of an html element.
direction margin-bottom:2Px
margin-top:3Px
margin-left:4Px
margin-right:5Px
Span
• It spans the content into sections.
• Each section can then have its own formatting, as specified by
the CSS.
• It is an inline container.
• No line break is created when a span is declared.
• In the following example all pizza restaurants names are
classed and styled.
• .pizza{font-size:24;font-weight:bold;color:#00ff00;text-
transform:uppercase;}
• International brans of Pizza include: <span class="pizza">
Domino's Pizza</span>,<span class="pizza">Pizza
Express</span>,<span class="pizza"> Pizza Hut</span>, etc.
• Output:
International brans of Pizza include: DOMINO'S
PIZZA,PIZZA EXPRESS,PIZZA HUT, ETC.
Div
• It spans the content into sections.
• Each section can then have its own formatting, as specified by the CSS.
• It is a block level container.
• There is a line break after div tag.
• In the following example all pizza restaurants names are classed and styled.
• .pizza{font-size:24;font-weight:bold;color:#00ff00;text-
transform:uppercase;}
• International brans of Pizza include: <div class="pizza"> Domino's
Pizza</div>,<div class="pizza">Pizza Express</div>,<div class="pizza">
Pizza Hut</div>, etc.
 
• OUTPUT
International brans of Pizza include:
DOMINO'S PIZZA
,PIZZA EXPRESS
,PIZZA HUT
,ETC.
StyleSheets in Asp.Net
(Visual Studio 2010)
Steps to Add a StyleSheet in Project
• Select the project path from Solution Explorer.
• Right click and select the Add New Item from the Popup Menu.

• Select StyleSheet from the list of items displayed in the Add Item Dialog
Box.
• Click Add Button.

• Now Open the StyleSheet file and Add relevant style definitions.
StyleSheet Example
.myclass
{
border:3px solid Green;
width: 200px;
height: 50px;
background-color:Aqua;
color: #FF00FF;
font-family:Times New Roman;
font-size:large;
font-weight: bold;

}
p
{
border:2px solid red;
width:100%;
Height:100px;
background-color:Olive;
color:White;
font-size:medium;
font-weight: bold;
}
Code to link a StyleSheet with a WebPage
• You can use a style sheet on the specific page where you want it by adding
reference like below.

<head runat="server">

<link href="StyleSheet1.css" rel="stylesheet" type="text/css" />

</head>

• Place the <link> tag within the <Head> </Head> tag of the
respective page.
Master Pages
• Master page provides a framework (common content as well as the
layout ) within which the content from other pages can be displayed.

• It provides elements such as headers, footers, style definitions, or


navigation bars that are common to all pages in your web site.

• So the Content Pages need not have to duplicate code for shared
elements within your Web site.

• It gives a consistent look and feel for all pages in your application.
Master Pages
Master Pages
Master Pages
• The master page layout consist of regions where the content from
each content page should be displayed.

• These regions can be set using ContentPlaceHolder server controls.

• These are the regions where you are going to have dynamic content
in your page.

• A derived page also known as a content page is simply a collection


of blocks the runtime will use to fill the regions in the master.
@ Master Directive
• The master page is identified by a special @ Master directive that
replaces the @ Page directive that is used for ordinary .aspx pages. 
• The @ Master directive defines attributes that are master page specific.
• Following are the important attributes of @ master directive:
• CodeFile:
Specifies the name of a separate file that contains source code associated
with the master page (code behind file of master page).
• Language:
Specifies the language used for any code required by the page. 
• Inherits:
Specifies a code-behind class for the page to inherit.
ContentPlaceHolder’s in Master Page
• Basically a master page has two content placeholders .
• The first one present within head element can be used for any element
that can be coded within the head element.
• In most cases you will use this content placeholder for a link element
that identifies an external style sheet for a content page.
• The second placeholder is used for displaying the content from each
content page.
ContentPlaceHolder’s in Master Page
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs"
Inherits="MasterPage" %>

<html>
<head runat="server"> <title></title>

<asp:ContentPlaceHolder id="head" runat="server">


</asp:ContentPlaceHolder>

</head><body> <form id="form1" runat="server">


<div>

<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">


</asp:ContentPlaceHolder>

</div></form></body>
</html>
What is the difference between a regular ASP Page and a Content Page?
Or
How to convert a regular ASP Page and a Content Page?

• A content file has to set MasterPageFile attribute of the Page directive to

the URL of the master page.

• Example:-

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"

AutoEventWireup="true" CodeFile="Default.aspx.cs"

Inherits="_Default" %>
Master Page Demo
MasterPage.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs"
Inherits="MasterPage" %>
<html > <head id="Head1" runat="server"> <title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head><body> <form id="form1" runat="server">
<center><table style="width:100%">
<tr><td colspan="2"> <center><h1 style="background: #C4376B;">
ASP.NET TUTOR</h1></center></td></tr>
<tr><td style=" background:#100000; width:400; height:1500; vertical-align:top; ">
<asp:treeview ShowLines="true" Font-Size="Large" ForeColor="White" ID="Treeview1"
runat="server" DataSourceID="SiteMapDataSource1"></asp:treeview>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
</td><td style=" vertical-align:top;">
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder></td></tr> </table></center>
</form></body></html>
Web.sitemap
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="Default.aspx" title="ASP.NET Master Pages"
description="">

<siteMapNode url="Default2.aspx" title="Diagrammatic Representation"


description="" />
<siteMapNode url="Default3.aspx" title="Advantages of Master Page"
description="" />
</siteMapNode>

</siteMap>
Default.aspx
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">


</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"


Runat="Server">

<h1>Master Pages</h1>
<ul style=" color:Maroon; line-height:60px; font-size:xx-large;">
<li>The master page layout consist of regions that each derived page can customize.</li>
<li>These regions can be set using ContentPlaceHolder server controls.</li>
<li>These are the regions where you are going to have dynamic content in your page.</li>
<li>A derived page also known as a content page is simply a collection of blocks the runtime
will use to fill the regions in the master.</li>
</ul>
</asp:Content>
Default2.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">


</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"


Runat="Server">
<img alt="Image of master page" style="width:1100;height:500;" src="masterp.jpg" />
</asp:Content>
Default3.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
<h1>Advantages of Master Controls</h1>
<ul style=" color:Maroon; line-height:60px; font-size:xx-large;">
<li>They allow you to centralize the common functionality of your pages so that you can make
updates in just one place. </li>
<li>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. </li>
<li>They give you fine-grained control over the layout of the final page by allowing you to
control how the placeholder controls are rendered. </li>
<li>They provide an object model that allows you to customize the master page from
individual content pages. </li>
</ul>
</asp:Content>
Advantages of Master Controls
• 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.
• They provide an object model that allows you to customize the
master page from individual content pages.

You might also like