Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

US05CBCA21 Advanced Web Development Technology

UNIT: 2 Information Passing, Standard Controls and Master Page

Passing Information from one page to another

Web Server Controls: Button, Image Button, Link Button, Textbox, Hyperlink,
ImageMap control (Creating Hotspots),CheckBox and RadioButton, CheckBoxList,
RadioButtonList, ListBox, DropdownList

Rich Controls: Calendar, Adrotator control (showing advertisement from XML file
and Database), FileUpload control

Grouping Controls: Panel, PlaceHolder

Using Navigation Controls: TreeView, SiteMapPath, Menu, Creating sitemap file for
navigation Designing Master page

1. Button

The Button is an asp.net web server control. This control is used to perform events. It is
also used to submit client request to the server. To create Button either we can write code
or use the drag and drop facility of visual studio IDE. We can display a simple push button
on a web page by adding button control on asp.net web page.

There are three type of button in asp.net.

1. Simple Push Button: Simple Push Button displays text on a button control.
2. Link Button: Link button displays text that looks like a link or hyperlink.
3. Image Button: Image Button displays an image on a button control.

These entire three buttons has main two events Click and Command events. By default in
asp.net button has click events.

This is a server side control and asp provides own tag to create it. The example is given below.

< asp:ButtonID="Button1" runat="server" Text="Submit" BorderStyle="Solid" ToolTip="Submit"/>

Server renders it as the HTML control and produces the following code to the browser.

<input name="Button1" value="Submit" id="Button1" title="Submit" style="border-


style:Solid;" type="submit">

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut for the control.


TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
PostBackUrl Path of the page when redirect while click the button.
OnClientClick write any client side script code function name.
2. ImageButton

Use of ImageButton control is to display an image that responds to mouse clicks. Both the
Click and Command events are raised when the ImageButton control is clicked. You
can use the OnCommand event handler to make the ImageButton control behave like a
Command button.

This is a server side control and asp provides own tag to create it.
<asp:ImageButton ID=”ImageButton1″ runat=”server” />

This control has its own properties that are tabled below.

Property Description

ID Identification of ImageButton control–


ImageUrl set image path to display image on image button control.
AlternateText AlternateText text display when image can not display on web page.
PostBackUrl Path of the page when redirect while click the Image button.
OnClientClick write JavaScript or any client side script code function name.

3. Link Button

It is a server web control that acts as a hyperlink. It is used to display a hyperlink-style


button control on the web page. ASP.NET provides a tag to create LinkButton and has
following syntax. The Link Button code is like:

<asp:LinkButton ID=”LinkButton1″ runat=”server”>LinkButton</asp:LinkButton>

Property Description

ID Identification of Link Button control


Text Display text on LinkButton like hyperlink.
PostBackUrl Path of the page when redirect while click the Link button.
OnClientClick write any client side script code function name.

4. Textbox

Textbox control is most usable web server control in asp.net. TextBox control is a
rectangular box which is used to take user to input. In simple word the TextBox is a place
where user can input some text on asp.net web form. To use TextBox on page we can write
code or just drag and drop from toolbox. This is server side control, asp provides own tag to
create it. The example is given below.
< asp:TextBoxID="TextBox1" runat="server" ></asp:TextBox>

Server renders it as the HTML control and produces the following code to the browser.

<input name="TextBox1" id="TextBox1" type="text">

Properties Description
5. Hyperlink
ID Identification name of textbox control.

Text It is used to display text in a control. HyperLink is an asp.net web


It is used to set background color of textbox server control. We can display a
BackColor control. hyperlink on a web page by
adding a hyplerlink control on
ForColor It is used to set text color of the control. asp.net web page.
HyperLink control used to
It displays a text on control when mouse over navigate user to anther page or
ToolTip on it. on the same page. It responds to
a click event. The main property
TabIndex It is used manage tab order of control. of hyperlink control
is NavigateUrl.
CssClass It is used to apply style on control. The NavigateUrl property of
hyperlink control store the
Enable true/false – used to enable or disable control.
address of destination page. The
true/false – It is used to hide or visible control HyperLink control display both as
Visible on web page. text and as image by
specifying Text or ImageUrl prop
It is used to set maximum number of characters erty of hyperlink control. If we set
MaxLenght that can be input in TextBox. any image in ImageUrl property
of hyperlink control then the
TextMode Single / Multiline / Password hyperlink display image on it.if we
set any text value in Text
true/false – used to enable or disable control Property of hyperlink control then
ReadOnly readonly. the hyperlink control display as
text link.

This is a server side control and ASP.NET provides own tag to create it. The example is
given below.
< asp:HyperLinkID="HyperLink1" runat="server" Text="JavaTpoint" NavigateUrl="www.javatpoint.com"
></asp:HyperLink>

Server renders it as the HTML control and produces the following code to the browser.

<a id="HyperLink1" href="www.javatpoint.com">JavaTpoint</a>


This control has its own properties that are tabled below.

Property Description

BackColor It is used to set background color of the control.


Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
NavigateUrl It is used to set navigate URL.
Target Target frame for the navigate url.
ImageUrl set image path to display image on control.

6. ImageMap Control

The ImageMap control in ASP.NET 2.0 and onward versions can be used to create an
image that contains defined hot spot regions. When a user clicks a hot spot region,
the control can either generate a post back to the server or navigate to a specified URL.

There are three kinds of hot spot regions defined in ImageMap control.

• RectangleHotSpot
• CircleHotSpot
• PolygonHotSpot

The RectangleHotSpot defines rectangular hot spot regions. The CircleHotSpotdefines circle-
shaped ones and the PolygonHotSpot is used for irregularly shaped hot spot area.

<asp:ImageMap ID="ImageMap1" runat="server" ImageUrl="~/Images/Hit Target.jpg"


onclick="ImageMap1_Click">
<asp:CircleHotSpot X="210" Y="210" Radius="20" NavigateUrl="Default.aspx"
AlternateText="Home Page" />
</asp:ImageMap>

This control has its own properties that are tabled below.

Property Description

ImageUrl Url of image location.

AlternetText Appears if image not loaded properly

Tooltip Appears when on mouse over the image

ImageAlign Used to align the Text beside image.

HotSpotMode PostBack/Navigate .... When Navigate, the user is navigated to a different URL. In
case of PostBack, the page is posted back to the server.

OnClick Attach a server side event that fires after clicking on image when HostSpotMode
is PostBack.

PostBackValue You can access it in the server side click event through ImageMapEventArgs. (eg.
e.PostBackValue)

7. CheckBox

It is used to get multiple inputs from the user. It allows user to select choices from the set of
choices. It takes user input in yes or no format. It is useful when we want multiple choices
from the user.

This is a server side control and ASP.NET provides own tag to create it. The example is given
below.

< asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE"/>

Server renders it as the HTML control and produces the following code to the browser.

< input id="CheckBox2" type="checkbox" name="CheckBox2" /><label for="CheckBox2">J2EE</label>

This control has its own properties that are tabled below.

Property Description

AutoPostBack Form is automatically posted back when CheckBox is checked or


Unchecked.

CausesValidation true/false. If true, Form is validated if Validation control has been used in the
form.

Checked true/false. If true, Check box is checked by default.

OnCheckedChanged Fires when CheckBox is checked or Unchecked. This works only


if AutoPostBack property is set to true.

ValidationGroup Used to put a checkbox under a particular validation group. It is used when
you have many set of form controls and by clicking a paricular button you
want to validate a particular set of controls only.

8. Radio Button

It is an input control which is used to takes input from the user. It allows user to select a choice
from the group of choices.

This is a server side control and ASP.NET provides own tag to create it. The example is given
below.

<asp:RadioButtonID="RadioButton1" runat="server" Text="Male" GroupName="gender"/>

Server renders it as the HTML control and produces the following code to the browser.

<input id="RadioButton1" type="radio" name="gender" value="RadioButton1" /><labelforlabelfor="Radi


oButton1">Male</label>
Following are some important properties that are very useful.

Property Description

AutoPostBack Form is automatically posted back when Radio button selection is changed.

CausesValidation true/false. If true, Form is validated if Validation control has been used in the
form.

Checked true/false. If true, Radio button is selected by default.

OnCheckedChanged Fires when Radio button selection changes. This works only
if AutoPostBack property is set to true.

ValidationGroup Used to put a radio button under a particular validation group. It is used
when you have many set of form controls and by clicking a paricular button
you want to validate a particular set of controls only.

GroupName It is used a group a set of radion buttons so only one of them can be
selected at a time.

9. ChechkboxList

CheckBoxList control is a single control that groups a collection of checkable list items,

Following are some important properties that are very useful.

Property Description

SelectedValue Gets the value of first selected item.

SelectedIndex Gets or Sets the index of the first selected item.

SelectedItem Gets the first selected item

TextAlign Gets or Sets the alignment of the checkbox text.

DataTextField Name of the data source field to supply the text of the items. (No need
to set when you are adding items directly into .aspx page.)

DataValueField Name of the data source field to supply the value of the items. (No
need to set when you are adding items directly into .aspx page.)

DataSourceID ID of the datasource component to provide data. (Only used when you
have any DataSource component on the page, like SqlDataSource,
AccessDataSource etc.)

DataSource The datasource that populates the items in the checkboxlist box.
(Generally used when you are dynamically generating the items from
Database.)

AutoPostBack true/false. If true, the form is automatically posted back to the server
when user click any of the checkbox. It will also
fire OnSelectedIndexChanged method.
AppendDataBoundItems true/false. If true, the statically added item (added from .aspx page) is
maintained when adding items dynamically (from code behind file) or
items are cleared.

OnSelectedIndexChanged Method name that fires when user click any of the checkbox in the list.
(Fires only when AutoPostBack=true.)

Items Gets the colleciton of the items from the list.

RepeatLayout table/flow. Gets or Sets the layout of the chekboxes when rendered to
the page.

RepeatColumns Gets or Sets the no. of columns to display when the control is
rendered.

RepeatDirection Horizontal/Vertical. Gets or Sets the the value to indicate whether the
control will be rendered horizontally or vertically.

10. RadioButtonList

RadioButtonList control is a single control that groups a collection of radiobuttons,

Note: RadioButtonList controls supports the same set of properties as the CheckBoxList
control does.

11. ListBox

ListBox control is an asp.net web server control. ListBox control used to store the multiple
items and allow user to select multiple item from listbox control. In a ListBox control there is
a SelectionMode property to change the mode of section from single to multiple. By
default listbox control selection mode is single if you want to select multiple items from
listbox, then just change the SelectionMode property to multiple.

Following are some important properties that are very useful.

Property Description

Rows No. of rows (items) can be set to display in the List.

SelectionMode Single or Multiple. If multiple, it allows user to select multiple items


from the list by holding Ctrl or Shift key.

SelectedValue Get the value of the Selected item from the dropdown box.

SelectedIndex Gets or Sets the index of the selected item in the dropdown box.

SelectedItem Gets the selected item from the list.

Items Gets the collection of items from the dropdown box.

DataTextField Name of the data source field to supply the text of the items.

DataValueField Name of the data source field to supply the value of the items.
DataSourceID ID of the datasource component to provide data.

DataSource The datasource that populates the items in the listbox box.

AutoPostBack true or false. If true, the form is automatically posted back to the server
when user changes the dropdown list selection.

AppendDataBoundItems true or false. If true, the statically added item (added from .aspx page)
is maintained when adding items dynamically (from code behind file)
or items are cleared.

OnSelectedIndexChanged Method name that fires when user changes the selection of the
dropdown box. (Fires only when AutoPostBack=true.)

12. DropDownList

The DropDownList control is asp.net web server control. We can use dropdownlist control for
hold group of items. The dropdownlist control is used to store the multiple items and allow
user to select only one item from it.The dropdownlist control is also known as combo box
control. In dropdownlist control we can store multiple items but we can select only one item at a
time, that’s why it is also known as Single Row Selection Box.

Following are some important properties that are very useful.

Property Description

SelectedValue Get the value of the Selected item from the dropdown box.

SelectedIndex Gets or Sets the index of the selected item in the dropdown box.

SelectedItem Gets the selected item from the list.

Items Gets the collection of items from the dropdown box.

DataTextField Name of the data source field to supply the text of the items.

DataValueField Name of the data source field to supply the value of the items.

DataSourceID ID of the datasource component to provide data.

DataSource The datasource that populates the items in the listbox box.

AutoPostBack true or false. If true, the form is automatically posted back to the server
when user changes the dropdown list selection. It will also
fire OnSelectedIndexChanged method.

AppendDataBoundItems true or false. If true, the statically added item (added from .aspx page)
is maintained when adding items dynamically (from code behind file)
or items are cleared.

OnSelectedIndexChanged Method name that fires when user changes the selection of the
dropdown box. (Fires only when AutoPostBack=true.)
Rich Controls:

ASP.NET - Calendars
The calendar control is a functionally rich web control, which provides the following capabilities:

• Displaying one month at a time


• Selecting a day, a week or a month
• Selecting a range of days
• Moving from month to month
• Controlling the display of the days programmatically
The basic syntax of a calendar control is:
<asp:Calender ID = "Calendar1" runat = "server">
</asp:Calender>

Properties and Events of the Calendar Control


The calendar control has many properties and events, using which you can customize the actions
and display of the control. The following table provides some important properties of the Calendar
control:
The Calendar control has the following three most important events that allow the developers to program
the calendar control. They are:

Working with the Calendar Control


Putting a bare-bone calendar control without any code behind file provides a workable calendar to
a site, which shows the months and days of the year. It also allows navigation to next and
previous months.

Calendar controls allow the users to select a single day, a week, or an entire month. This is done by using
the SelectionMode property. This property has the following values:

The syntax for selecting days:


<asp:Calender ID = "Calendar1" runat = "server"
SelectionMode="DayWeekMonth">
</asp:Calender>

When the selection mode is set to the value DayWeekMonth, an extra column with the > symbol appears
for selecting the week, and a >> symbol appears to the left of the days name for selecting the month.

Example
The following example demonstrates selecting a date and displays the date in a label:
The content file code is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"


Inherits="calendardemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
<title>
Untitled Page
</title>
</head>

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

<div>
<h3> Your Birthday:</h3>
<asp:Calendar ID="Calendar1" runat="server
SelectionMode="DayWeekMonth"
onselectionchanged="Calendar1_SelectionChanged">
</asp:Calendar>
</div>

<p>Todays date is:


<asp:Label ID="lblday" runat="server"></asp:Label>
</p>

<p>Your Birday is:


<asp:Label ID="lblbday" runat="server"></asp:Label>
</p>

</form>
</body>
</html>

The event handler for the event SelectionChanged:


protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
lblday.Text = Calendar1.TodaysDate.ToShortDateString();
lblbday.Text = Calendar1.SelectedDate.ToShortDateString();
}

When the file is run, it should produce the following output:

AdRotator Control:

The AdRotator is one of the rich web server control of asp.net. AdRotator control is used
to display a sequence of advertisement images as per given priority of image.

The AdRotator control randomly selects banner graphics from a list, which is specified in an
external XML schedule file. This external XML schedule file is called the advertisement file.
The AdRotator control allows you to specify the advertisement file and the type of window that the
link should follow in the AdvertisementFile and the Target property respectively.

In a Adrotator control images will be changed each time while refreshing the web page.

The basic syntax of adding an AdRotator is as follows:


<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target =
"_blank" />

The Advertisement File


The advertisement file is an XML file, which contains the information about the advertisements to
be displayed.
Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-
based markup language that enables you to store data in a structured format by using meaningful
tags. The term 'extensible' implies that you can extend your ability to describe a document by
defining meaningful tags for the application.
XML is not a language in itself, like HTML, but a set of rules for creating new markup languages.
It is a meta-markup language. It allows developers to create custom tag sets for special uses. It
structures, stores, and transports the information.

Following is an example of XML file:


<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>

Like all XML files, the advertisement file needs to be a structured text file with well-defined tags
delineating the data. There are the following standard XML elements that are commonly used in
the advertisement file:
Properties and Events of the AdRotator Class
The AdRotator class is derived from the WebControl class and inherits its properties. Apart from
those, the AdRotator class has the following properties:
Following are the important events of the AdRotator class:

Working with AdRotator Control


Create a new web page and place an AdRotator control on it.
<form id="form1" runat="server">
<div>
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile
="~/ads.xml" onadcreated="AdRotator1_AdCreated" />
</div>
</form>

The ads.xml file and the image files should be located in the root directory of the web site.
Try to execute the above application and observe that each time the page is reloaded, the ad is
changed.

AdRotator Control Example in ASP.Net


Step 1 – Open the Visual Studio –> Create a new empty Web application.

Step 2 – Create a New web page for display AdRotator control.

step 3 – Drag and drop AdRotator Control on web page from toolbox.

step 4 – go to Add New Item –> Add New XML File in project for write advertisement detail.
step 5 – Assign XML File to AdvertisementFile Property of AdRotator control.

Now, let’s understand the adrotator control with an asp.net example.

Adrotator Control in ASP.Net C#


Create a asp.net web application and take an adrotator control on web forms like below:

Now, Add new XML file by going to add new item menu.

Select XML file, assign any name for xml file and click Add button to add new xml file.
write below code for advertisement in xml file
The XML file contain the advertisement information.
ImageUrl describe the path of image which is display in adrotator.

Advertisement XML File for Adrotator Control


Now, assign the XML file to adrotator control by AdvertisementFile property of
adrotator control.
ASP.NET - File Uploading
ASP.NET has two controls that allow users to upload files to the web server. Once the server
receives the posted file data, the application can save it, check it, or ignore it. The following
controls allow the file uploading:
• HtmlInputFile - an HTML server control
• FileUpload - and ASP.NET web control
Both controls allow file uploading, but the FileUpload control automatically sets the encoding of
the form, whereas the HtmlInputFile does not do so.
In this tutorial, we use the FileUpload control. The FileUpload control allows the user to browse
for and select the file to be uploaded, providing a browse button and a text box for entering the
filename.
Once, the user has entered the filename in the text box by typing the name or browsing, the
SaveAs method of the FileUpload control can be called to save the file to the disk.
The basic syntax of FileUpload is:
<asp:FileUpload ID= "Uploader" runat = "server" />

The FileUpload class is derived from the WebControl class, and inherits all its members. Apart from those,
the FileUpload class has the following read-only properties:

The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed
through the PostedFile property of the FileUpload class.
The HttpPostedFile class has the following frequently used properties:
Example
The following example demonstrates the FileUpload control and its properties. The form has a
FileUpload control along with a save button and a label control for displaying the file name, file
type, and file length.
In the design view, the form looks as follows:

The content file code is as given:

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

<div>
<h3> File Upload:</h3>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />
<asp:Button ID="btnsave" runat="server" onclick="btnsave_Click"
Text="Save" style="width:85px" />
<br /><br />
<asp:Label ID="lblmessage" runat="server" />
</div>

</form>
</body>

The code behind the save button is as given:


protected void btnsave_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();

if (FileUpload1.HasFile)
{
try
{
sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);

//saving the file


FileUpload1.SaveAs("<c:\\SaveDirectory>" + FileUpload1.FileName);

//Showing the file information


sb.AppendFormat("<br/> Save As: {0}",
FileUpload1.PostedFile.FileName);
sb.AppendFormat("<br/> File type: {0}",
FileUpload1.PostedFile.ContentType);
sb.AppendFormat("<br/> File length: {0}",
FileUpload1.PostedFile.ContentLength);
sb.AppendFormat("<br/> File name: {0}",
FileUpload1.PostedFile.FileName);

}catch (Exception ex)


{
sb.Append("<br/> Error <br/>");
sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
}
}
else
{
lblmessage.Text = sb.ToString();
}
}

Note the following:


• The StringBuilder class is derived from System.IO namespace, so it needs to be included.
• The try and catch blocks are used for catching errors, and display the error message.

CONTAINER OR GROUPING CONTROLS:

There are two grouping controls:

1) Panel control
2) PlaceHolder control
1) Panel Control:
The Panel Web server control provides a container control in an ASP.NET Web page that user can use as a parent for
static text and for other controls.

User can use the Panel control as a container for other controls.
Properties Description
BackImageUrl Specifies a URL to an image file to display as a background for this control.
GroupingText Title of the Panel. The text of group box around this control's contents.
HorizontalAlign Specifies the horizontal alignment of the content. Legal values are :
1) Center
2) Justify
3) Left
4) NotSet
5) Right
Scrollbar The appearance of scrollbars for the panel.
Wrap A Boolean value that specifies whether the content should wrap or not.
2) PlaceHolder Control:
➢ The PlaceHolder control allows user to place an empty container control in the page and then dynamically to add
child elements to it at run time.
➢ It does not have any visible output and is used as a place holder when we add controls at run time.
➢ The placeholder control saves a spot for you to programmatically add or remove controls.
➢ User can add or remove as many controls as you want to the placeholder control.
➢ Use the Add method to add controls to the placeholder and remove method to remove them.

Difference between Panel vs. PlaceHolder:


SITE NAVIGATION AND SITE MAPS

You’ve already learned simple ways to send a website visitor from one page to another. For
example, you can add HTML links (or HyperLink controls) to your page to let users surf through
your site. If you want to perform page navigation in response to another action, you can call the
Response.Redirect() method or the Server.Transfer() method in your code. But in professional
web applications, the navigation requirements are more intensive. These applications need a
system that allows users to surf through a hierarchy of pages, without forcing you to write the
same tedious navigation code in every page.

Site Maps

ASP.NET navigation is flexible, configurable, and pluggable. It consists of three components:

• A way to define the navigational structure of your website. This part is the XML site map,
which is (by default) stored in a file.
• A convenient way to read the information in the site map file and convert it to an object
model. The SiteMapDataSource control and the XmlSiteMapProvider perform this part.
• A way to use the site map information to display the user’s current position and give the user
the ability to easily move from one place to another. This part takes place through the
navigation controls you bind to the SiteMapDataSource control, which can include
breadcrumb links, lists, menus, and trees.

You can customize or extend each of these ingredients separately. For example, if you want to
change the appearance of your navigation controls, you simply need to bind different controls to
the SiteMapDataSource. On the other hand, if you want to read site map information from a
different type of file or from a different location, you need to change your site map provider.

Figure shows how these pieces fit together.

Defining a Site Map

You can create it in Visual Studio by right on Website ➤ Add New Item and then choosing the
Site Map option.

Rules for creating Site Maps:

Rule 1: Site Maps Begin with the <siteMap> Element

Every Web.sitemap file begins by declaring the <siteMap> element and ends by closing that
element. You place the actual site map information between the start and end tags

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">

.......

…….
…….

</siteMap>

Rule 2: Each Page Is Represented by a <siteMapNode> Element

To insert a page into the site map,

Add the <siteMapNode> element with some basic information.

• Namely, you need to supply the title of the page (which appears in the navigation
controls),
• a description (which you may or may not choose to use),
• the URL (the link for the page).

You add these three pieces of information using three attributes. The attributes are named title,
description, and url, as shown here:

<siteMapNode description="CLASS" title="CLASS LIST" url="~/CLASS.aspx">

Here’s a complete, valid site map file that uses this page to define a website with exactly one
page:

<?xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode description="CLASS" title="CLASS LIST" url="~/CLASS.aspx">

<siteMapNode description="FYBCA" title="FYBCA" url="~/FYBCA.aspx"/>

</siteMapNode>

</siteMap>

Rule 3: A <siteMapNode> Element Can Contain Other <siteMapNode> Elements

Site maps don’t consist of simple lists of pages. Instead, they divide pages into groups. To
represent this in a site map file, you place one <siteMapNode> inside another. Instead of using
the empty element syntax shown previously, you’ll need to split your <siteMapNode> element
into a start tag and an end tag:
<?xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode description="CLASS" title="CLASS LIST" url="~/CLASS.aspx">

<siteMapNode description="SEM-I" title="SEM-I" url="~/SEM1.aspx" />

<siteMapNode description="SEM-II" title="SEM-II" url="~/SEM2.aspx" />

<siteMapNode description="SEM-III" title="SEM-III" url="~/SEM3.aspx" />

</siteMapNode>

</siteMap>

When you show this part of the site map in a web page, the Products node will appear as
ordinary text, not a clickable link.

Figure : Three node in a site map

Rule 4: Every Site Map Begins with a Single <siteMapNode>

Rule 5: Duplicate URLs Are Not Allowed

Binding an Ordinary Page to a Site Map

To bind the site Map to the page , add the SiteMapDataSource control to your page. You can
drag and drop it from the Data tab of the Toolbox. It creates a tag like this:
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

The SiteMapDataSource control appears as a gray box on your page in Visual Studio, but

it’s invisible when you run the page.

The last step is to add controls that are linked to the SiteMapDataSource

These are the three navigation controls:

TreeView: The TreeView displays a “tree” of grouped links that shows your whole site map at a
look.

Menu: The Menu displays a multilevel menu. By default, you’ll see only the first level, but other
levels pop up when you move the mouse over the subheadings.

SiteMapPath: The SiteMapPath is the simplest navigation control—it displays the full path you
need to take through the site map to get to the current page. For example, it might show

CLASS > SEM I > US01CBCA03

To connect a control to the SiteMapDataSource, you simply need to set its DataSourceIDproperty
to match the name of the SiteMapDataSource.

For example, if you added a TreeView, you should tweak the tag so it looks like this:

For Menu
Binding a Master Page to a Site Map

Website navigation works best when combined with another ASP.NET feature—master pages.

That’s because you’ll usually want to show the same navigation controls on every page. The
easiest way to do this is to create a master page that includes the SiteMapDataSource and the
navigation controls. You can then reuse this template for every other page on your site.

Here’s how you might define a basic structure in your master page that puts navigation controls
on the left:

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>

<html>

<head runat="server">

<title>Navigation Test</title>

</head>

<body>

<form id="form1" runat="server">

<table>

<tr>

<td style="width: 226px;vertical-align: top;">

<asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1" />

</td>

<td style="vertical-align: top;">

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


</td>

</tr>

</table>

<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

</form>

</body>

</html>

Then, create a child with some simple static content:

Using Different Site Maps in the Same File

Imagine you want to have a dealer section and an employee section on your website. You

might split this into two structures and define them both under different branches in the same

file, like this:

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode title="Root" description="Root" url="~/default.aspx">

<siteMapNode title="Dealer Home" description="Dealer Home"

url="~/default_dealer.aspx">

...

</siteMapNode>

<siteMapNode title="Employee Home" description="Employee Home"

url="~/default_employee.aspx">

...

</siteMapNode>

</siteMapNode>

</siteMap>

To bind the SiteMapDataSource to the dealer view (which starts at the Dealer Home page),

you simply set the StartingNodeUrl property to “~/default_dealer.aspx”.

You can even make your life easier by breaking a single site map into separate files using

the siteMapFile attribute, like this:


<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode title="Root" description="Root" url="~/default.aspx">

<siteMapNode siteMapFile="Dealers.sitemap" />

<siteMapNode siteMapFile="Employees.sitemap" />

</siteMapNode>

</siteMap>

SiteMapNode Navigational Properties

Property Description

ParentNode Returns the node one level up in the navigation hierarchy, which contains
the

current node. On the root node, this returns a null reference.

ChildNodes Provides a collection of all the child nodes. You can check the HasChildNodes

property to determine whether child nodes exist.

PreviousSibling Returns the previous node that’s at the same level (or a null reference if no
such

node exists).

NextSibling Returns the next node that’s at the same level (or a null reference if no such

node exists).

To see this in action, consider the following code, which configures two labels on a page to show
the heading and description information retrieved from the current node:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

lblHead.Text = SiteMap.CurrentNode.Title

lblDescription.Text = SiteMap.CurrentNode.Description

End Sub
If you’re using master pages, you could place this code in the code-behind for your master page,
so that every page is assigned its title from the site map.

The next example is a little more ambitious. It implements a Previous/Next set of links, allowing
the user to traverse an entire set of subnodes. The code checks for the existence of sibling nodes,
and if there aren’t any in the required position, it simply hides the links:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

If SiteMap.CurrentNode.NextSibling IsNot Nothing Then

lnkNext.NavigateUrl = SiteMap.CurrentNode.NextSibling.Url

lnkNext.Visible = True

Else

lnkNext.Visible = False

End If

End Sub

The first picture shows the Next link on the product1.aspx

page. The second picture shows how this link disappears when you navigate to product2.aspx

(either by clicking the Next link or the RevoAnalyze link in the TreeView).
Mapping URLs

You define URL mapping in the <urlMappings> section of the web.config file. You supply

two pieces of information—the request URL (as the attribute url) and the new destination URL

(mappedUrl). Here’s an example:

<configuration>

<system.web>

<urlMappings enabled="true">
<add url="~/category.aspx" mappedUrl="~/default.aspx?category=default" />

<add url="~/software.aspx" mappedUrl="~/default.aspx?category=software" />

</urlMappings>

...

…..

…..

</system.web>

</configuration>

The SiteMapPath Control

The TreeView shows the available pages, but it doesn’t indicate where you’re currently
positioned.

To solve this problem, it’s common to use the TreeView in conjunction with the SiteMapPath
control. Because the SiteMapPath is always used for displaying navigational information (unlike
the TreeView, which can also show other types of data), you don’t even need to explicitly link it to
the SiteMapDataSource:

<asp:SiteMapPath ID="SiteMapPath1" runat="server" />

The SiteMapPath provides breadcrumb navigation, which means it shows the user’s current
location and allows the user to navigate up the hierarchy to a higher level using links.

Following Figure shows an example with a SiteMapPath control when the user is on the
product1.aspx page. Using the SiteMapPath control, the user can return to the default.aspx
page.
Breadcrumb navigation with SiteMapPath

SiteMapPath Appearance-Related Properties

Property Description

ShowToolTips Set this to False if you don’t want the description text to
appear when the user hovers over a part of the site map path.

ParentLevelsDisplayed This sets the maximum number of levels above the current
page that will be shown at once. By default, this setting is -1,
which means all levels will be shown

RenderCurrentNodeAsLink If True, the portion of the page that indicates the current page
is turned into a clickable link. By default, this is False
because the user is already at the current page.

PathDirection You have two choices: RootToCurrent (the default) and


CurrentToRoot (which reverses the order of levels in the path).

PathSeparator This indicates the characters that will be placed between each
level in the path. The default is the greater-than symbol (>).
Another common path separator is the colon (:).

Using SiteMapPath Styles and Templates


Style Template Applies To

NodeStyle NodeTemplate All parts of the path except the root and

current node

CurrentNodeStyle CurrentNodeTemplate The node representing the current page.

RootNodeStyle RootNodeTemplate The node representing the root. If the


root

node is the same as the current node,


the

current node template or styles are used.

PathSeparatorStyle PathSeparatorTemplate The separator in between each node

Imagine you want to change how the current node is displayed so that it’s shown in italics.

To get the name of the current node, you need to write a data-binding expression that retrieves
the title.

This data-binding expression is bracketed between <%# and %> characters and uses a method
named Eval() to retrieve information from a SiteMapNode object that represents a page.

Here’s what the template looks like:

<asp:SiteMapPath ID="SiteMapPath1" runat="server">

<CurrentNodeTemplate>

<i><%# Eval("Title") %></i>

</CurrentNodeTemplate>

</asp:SiteMapPath>

Data binding also gives you the ability to retrieve other information from the site map node, such
as the description. Consider the following example:
<asp:SiteMapPath ID="SiteMapPath1" runat="server">

<PathSeparatorTemplate>

<asp:Image ID="Image1" ImageUrl="~/arrowright.gif" runat="server" />

</PathSeparatorTemplate>

<RootNodeTemplate>

<b>Root</b>

</RootNodeTemplate>

<CurrentNodeTemplate>

<%# Eval("Title") %> <br />

<small><i><%# Eval("Description") %></i></small>

</CurrentNodeTemplate>

</asp:SiteMapPath>

A SiteMapPath with templates


The TreeView Control
the TreeView can show a portion of the full site map or the entire site map. Each node

becomes a link that, when clicked, takes the user to the new page. If you hover over a link, you’ll

see the corresponding description information appear in a tooltip.

TreeView Properties

Useful TreeView Properties


Property Description
MaxDataBindDepth Determines how many levels the TreeView will show. By
default, MaxDataBindDepth is -1, and you’ll see the entire
tree. However, if you use a value such as 2, you’ll see only
two levels under the starting node. This can help you pare
down the display of long, multileveled site maps.
ExpandDepth Lets you specify how many levels of nodes will be visible at
first. If you use 0, the TreeView begins completely closed.
If you use 1, only the first level is expanded, and so on. By
default, ExpandDepth is set to the constant FullyExpand
(-1), which means the tree is fully expanded and all the
nodes are visible on the page.

NodeIndent Sets the number of pixels between each level of nodes in


the TreeView. Set this to 0 to create a nonindented
TreeView, which saves space. A nonindented TreeView
allows you to emulate an in-place menu (see, for example,
Figure 14-12).
ImageSet Lets you use a predefined collection of node images for
collapsed, expanded, and nonexpandable nodes. You
specify one of the values in the TreeViewImageSet
enumeration. You can override any node images you want
to change by setting the CollapseImageUrl,
ExpandImageUrl, and NoExpandImageUrl properties.
Sets the pictures that are shown next to nodes for
CollapseImageUrl,
collapsed nodes
ExpandImageUrl, (CollapseImageUrl) and expanded nodes
and (ExpandImageUrl). The
NoExpandImageUrl NoExpandImageUrl is used if the node doesn’t have any
children. If you don’t want to create your own custom
node images, you can use the ImageSet property instead
to use one of several built-in image collections.
Lets a node text wrap over more than one line when set to
NodeWrap
True.
ShowExpandCollapse Hides the expand/collapse boxes when set to False. This
isn’t recom-mended, because the user won’t have a way to
expand or collapse a level without clicking it (which causes
the browser to navigate to the page).
ShowLines Adds lines that connect every node when set to True.
ShowCheckBoxes
Shows a check box next to every node when set to True.
This isn’t terribly useful for site maps, but it is useful with
other types of trees.

TreeView Styles
Styles are represented by the TreeNodeStyle class, which derives from the more conventional
Style class.

Table : TreeNodeStyle-Added Properties

Property Description
ImageUrl The URL for the image shown next to the node.
NodeSpacing The space (in pixels) between the current node and the node
above and below.
The space (in pixels) between the top and bottom of the node
VerticalPadding
text and border around the text.
HorizontalPadding The space (in pixels) between the left and right of the node text and
border around the text.

The space (in pixels) between the last child node of an expanded
ChildNodesPadding parent node and the following node (for example, between the
Investing and Products nodes in above (sitemap template) Figure ).

Applying Styles to Node Types

The TreeView allows you to individually control the styles for types of nodes—for example, root
nodes, nodes that contain other nodes, selected nodes, and so on. Table lists different TreeView
styles and explains what nodes they affect.

Table: TreeView Style Properties

Property Description
NodeStyle Applies to all nodes. The other styles may override some or
all of the details that are specified in the NodeStyle.
RootNodeStyle Applies only to the first-level (root) node.
Applies to any node that contains other nodes, except root
ParentNodeStyle
nodes.
Applies to any node that doesn’t contain child nodes and
LeafNodeStyle
isn’t a root node.
SelectedNodeStyle Applies to the currently selected node.
HoverNodeStyle Applies to the node the user is hovering over with the
mouse. These settings are applied only in up-level clients
that support the necessary dynamic script.

For example
<asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1">

<NodeStyle Font-Names="Tahoma" Font-Size="10pt" ForeColor="Blue"

HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" />

<ParentNodeStyle Font-Bold="False" />

<HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />

<SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" />

</asp:TreeView>

The Menu Control


The Menu control is another rich control that supports hierarchical data. Like the TreeView, you
can bind the Menu control to a data source, or you can fill it by hand using MenuItem objects.

To try the Menu control, remove the TreeView from your master page, and add the following

Menu control tag:

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" />


Navigating through the menu

Difference between tree view and Menu as follow:

• The Menu displays a single submenu. The TreeView can expand an arbitrary number of
node branches at a time.
• The Menu displays a root level of links in the page. All other items are displayed using fly-
out menus that appear over any other content on the page. The TreeView shows all its
items inline in the page.
• The Menu supports templates. The TreeView does not. (Menu templates are discussed
later in this section.)
• The TreeView supports check boxes for any node. The Menu does not.
• The Menu supports horizontal and vertical layouts, depending on the Orientation
property. The TreeView supports only vertical layout.

Menu Styles

The Menu supports defining different menu styles for different menu levels.

Table Menu Styles

Static Style Dynamic Style Description

StaticMenuStyle DynamicMenuStyle Sets the appearance of the overall “box” in


which all the menu items appear. In the
case of StaticMenuStyle, this box appears
on the page, and with DynamicMenuStyle it
appears as a pop-up.

StaticMenuItemStyle DynamicMenuItemStyle Sets the appearance of individual menu


items
StaticSelectedStyle DynamicSelectedStyle Sets the appearance of the selected item.
Note that the selected item isn’t the item
that’s currently being hovered over; it’s the
item that was previously clicked (and that
triggered the last postback)

StaticHoverStyle DynamicHoverStyle Sets the appearance of the item that the


user is hovering over with the mouse.

Following Figure shows the menu with StaticDisplayLevels set to 2 (and some styles applied
through the Auto Format link).

A menu with two static levels

Master Page:

➢ MasterPages allow user to create a consistent look and behavior for all the pages (or group of pages) in your
web application.
➢ MasterPage means not Homepage.
➢ MasterPage support was one of the most popular features introduced with ASP.NET 2.0.
➢ A MasterPage provides a template for other pages, with shared layout and functionality.
➢ If user wants to display standard header, footer and menu in each page of the website, then user can create the
standard header, footer and menu in a MasterPage.
➢ Master pages help us to build consistent and maintainable user interfaces.
➢ They allow user to layout a page once and use it over and over.
➢ The master page defines placeholders for the content, which can be overridden by content pages. The output
result is a combination of the master page and the content page.
➢ The content page contains the content which user wants to display.
Characteristics:

➢ Extension of MasterPage is '.master'


➢ Master page also have codebehind file.
➢ We cannot run MasterPage directly.
➢ MasterPage can be nested.
➢ It allows user to centralize the common functionality of their pages so that user can make updates in just one
place.
➢ Website can contain many MasterPages.
➢ User can create multiple master pages to define different layouts for parts of the Site, and a different set of
content pages for each master page.
➢ Masterpage make it easy to create one set of controls and code and apply the results to a set of pages. For
example, user can use controls on the MastetPage to create a menu that applies to all pages.
➢ A MasterPage has 2 parts.
1) Content that appears on each page that inherits the master page.
2) Regions that can be customized by the pages inheriting the master page.

➢ A Masterpage needs to specify both the parts common to all pages and the parts that are customizable.
➢ Items you add to the master page appear on all pages that inherit it.
➢ Use ContentPlaceHolder controls to specify a region that can be customized.
➢ MasterPage should contain at least one ContentPlaceHolder.
➢ Runtime user can change the MasterPage.
➢ The declaration for a MasterPage:
<%@Master Language="VB" CodeFile="SimpleCMS.master.cs" Inherits="SimpleCMS" %>

This tells the underlying ASP.NET framework how to handle this special page.

➢ Runtime Masterpage and Normalpage (ContentPage) will merge.


➢ User can access any of the control of Masterpage from ContentPage.
➢ When we use the concept of MasterPage normal content page does not have <html> <head> <title> or even
<body> tag.
➢ When user associate a master page with a content page, the content page automatically includes the title
attribute.

ContentPlaceHolder:

➢ Content placeholders are used to allocate places on the MasterPage that will be changed on the content pages.
➢ Content placeholder is a control in MasterPage. The content from the content page appears in the area made by
content placeholder control.
➢ There are two ContentPlaceHolder on any MasterPage.
1) In the Head section
2) In the between <form> </form>
➢ In the head user can specify certain Meta fields such as the page description and keywords. These vary from
page to page so if you're using a Master Page then this is where you would put one Place Holder.
➢ In the form section the actual webpage contents will paste.
➢ User can have multiple ContentPlaceHolders on the same page.

Content Pages:

➢ The content pages contain the content which user wants to display.
➢ For example, Home.aspx, Aboutus.aspx, Contactus.aspx, CheckMail.aspx, ContentPages, etc. are Content pages.
➢ User can define the content for the master page's placeholder controls by creating individual content pages,
which are ASP.NET pages that are bound to specific master page.
➢ When users request the content pages, they merge with the MasterPage to produce output that combines the
layout of the MasterPage with content from the content page.

Theme:

➢ Themes are an extension of another idea, like Master Pages. But Themes are different than Master Pages.
➢ A Master Page enables user to share content across multiple pages in a website.
➢ While Theme enables user to control the appearance of the content.
➢ A theme is a collection of property settings that allows user 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.
➢ The concept is like, while one user may be visiting your site and seeing it one way, another user can be viewing
the exact same site, but get a completely different experience.
➢ Themes can be thought of as a container where user can store their own style sheets, images, skin files, etc.
➢ To apply theme to the web application, add new folder App_Theme by right clicking on Web Project.
➢ Themes are applied on the server. So we can change it runtime.
➢ A Theme folder can contain a variety of different types of files:
1) Skins
2) Cascading style sheets (CSS)
3) Images and other resources.

➢ Themes are control-based, not HTML-based. One of the advantages of Themes is that unlike CSS (only HTML
Controls) it allows user to define and reuse almost any control property.
➢ Themes can be applied through configuration file. In case if you want to have the luxury to apply a single theme
on the whole website you can do that too. You just have to apply it through configuration files for this purpose.
➢ Only one theme can be applied to each page.
Skin File:

➢ A skin generally contains visual properties (for look and feel strategies) of ASP.NET controls (server controls).
➢ The extension of skin file is .skin.
➢ It contains property settings for individual controls such as Button, Label, Textbox, Calendar etc. server side
controls.
➢ User can define skins in a separate file for each control or define all the skins for a theme in a single file.
➢ There are two types of skin files.
1) Default Skin
2) Named Skin
1) Default Skin :
➢ Default skin automatically applies to all controls of the same type when a theme is applied to a page.
➢ The SkinId is not defined.
➢ Only one default control skin per control type is allowed in the same theme.

2) Named Skin:
➢ It is a control skin with a SkinID property set.
➢ Named skins do not automatically apply to controls by type.
➢ In named skin, user can decide when you want to apply the skin.
➢ The Skinld should be uniquely defined because duplicate Skinld's per control type are not allowed in the same
theme.

CSS File:

➢ A Cascading Style Sheet (CSS) may be added to a Theme by placing it under the named Theme subdirectory.
➢ When user puts a .css file in the theme directory, the style sheet is applied automatically as a part of the theme.
➢ The CSS stylesheet will be applied to all pages with that theme applied.
➢ The Extension of the CSS file is .css.

You might also like