You are on page 1of 37

ASP.

NET
Table of Contents
1 Prerequisites: ............................................................................................................................... 3
2 What is ASP.NET? ......................................................................................................................... 3
3 What is C#? .................................................................................................................................. 3
4 Where to code?............................................................................................................................ 4
5 Installing Visual Studio 2015 ........................................................................................................ 4
6 Life Cycle ...................................................................................................................................... 6
6.1 Life cycle of ASP.NET Application.......................................................................................... 6
6.2 Life cycle of ASP.NET page .................................................................................................... 6
6.3 Life cycle events of ASP.NET page ........................................................................................ 7
7 Introduction to Web Forms ......................................................................................................... 9
7.1 Sample Application .............................................................................................................. 9
8 Controls and Events ................................................................................................................... 12
8.1 Web Server Controls ........................................................................................................... 12
8.2 Event Arguments................................................................................................................. 12
8.3 Textbox control ................................................................................................................... 13
8.4 Button control ..................................................................................................................... 14
9 Data Binding ............................................................................................................................... 15
9.1 Data binding to an ArrayList ............................................................................................... 15
9.2 Data binding to Hashtable .................................................................................................. 17

9.3 Data binding to SortedList .................................................................................................. 20


9.4 Data binding to XML file...................................................................................................... 22
10 DataList Control ....................................................................................................................... 26
11 Master Pages............................................................................................................................ 30
12 Navigation ................................................................................................................................ 32
12.1 The Sitemap File ................................................................................................................ 32
12.2 Dynamic Menu: ................................................................................................................. 33
12.3 TreeView ........................................................................................................................... 34
12.4 SiteMapPath...................................................................................................................... 35
13 Validation Controls .................................................................................................................. 36

1 Prerequisites:
It will be good if you have knowledge about HTML and CSS before starting with ASP.NET.

2 What is ASP.NET?
ASP.NET is a server side programming language. In server side scripting languages, all
calculations are done by the server on which the site is hosted on.
ASP.NET is a web development platform, developed by Microsoft. It is part of Microsoft .NET
platform.
ASP.NET programming is generally done using the following languages.
VB.NET : Visual Basic
C# : C sharp
In this tutorial, we will be programming in C#.

3 What is C#?
C# is a modern, general-purpose, object-oriented programming language developed by
Microsoft. C# enables developers to build robust and secure applications that run on the .NET
Framework. Syntax of C# looks similar to C, C++ and Java but it is more flexible that these
languages. As an object-oriented language, C# supports the concepts of encapsulation,
inheritance and polymorphism.

4 Where to code?
The following development tools can be used for ASP.NET coding.
WebMatrix
Visual Web Developer
Visual Studio
In this tutorial, we are going to work with Visual Studio 2015. Visual Studio is an integrated
development environment for writing, compiling, and debugging the code. It provides a set of
development tools for building ASP.NET web applications, desktop applications, and mobile
applications.

5 Installing Visual Studio 2015


Microsoft provides a free version of Visual Studio along with SQL Server included in it.
You can download it from here www.visualstudio.com.
After downloading and installing visual studio, open it. It will look something like this.

Now go to File menu -> New -> Project -> Web -> ASP.NET Web Application and click OK. Select
the template called Web Forms and click OK.
Open the Solution Explorer(on the right) and you will see a number of files present there.
The file named Default.aspx contains the HTML and asp code that defines the form, and the file
named Default.aspx.cs contains the code in the language you have chosen and this code is
responsible for the actions performed on a form.
File

Purpose

Default.aspx

Typically the first page displayed when the application is run in a browser.

Site.Master

A page that allows you to create a consistent layout and use standard
behavior for pages in your application.

Global.asax

An optional file that contains code for responding to application-level and


session-level events raised by ASP.NET or by HTTP modules.

Web.config

The configuration data for an application.

A sample web application code will already be present. To execute the application click
Start(upper middle in VS window) or click F5.

6 Life Cycle
6.1 Life cycle of ASP.NET Application
When user sends a request for accessing a web application or page:
Browser sends this request to the web server(IIS).
An object of ApplicationManager class is created. This is the application domain that the
request is processed in.
An object of HostingEnvironment is created. This provides access to information about
the application.
After instantiating HostingEnvironment object, application objects such as HttpContext,
HttpRequest and HttpResponse are created and initialized.
Then the HttpApplication object is created and assigned to the application objects to
process the page.
The request is processed by HttpApplication through events using modules, handlers,
page.

6.2 Life cycle of ASP.NET page


When a page is requested, it is loaded into the server memory, processed, and sent to the
browser. Then it is unloaded from the memory. At each of these steps, methods and events are
available, which could be overridden according to the need of the application.
The different stages of an ASP.NET page are as follows:
Page request : When ASP.NET gets a page request, it decides whether to parse and
compile the page, or there would be a cached version of the page; accordingly the
response is sent.

Starting of page life cycle : At this stage, the Request and Response objects are set. If the
request is an old request or post back, the IsPostBack property of the page is set to true.
The UICulture property of the page is also set.
Page initialization : At this stage, the controls on the page are assigned unique ID by
setting the UniqueID property and the themes are applied. For a new request, postback
data is loaded and the control properties are restored to the view-state values.
Page load : At this stage, control properties are set using the view state and control
state values.
Validation : Validate method of the validation control is called and on its successful
execution, the IsValid property of the page is set to true.
Postback event handling : If the request is a postback (old request), the related event
handler is invoked.
Page rendering : At this stage, view state for the page and all controls are saved. The
page calls the Render method for each control and the output of rendering is written to
the OutputStream class of the Response property of page.
Unload : The rendered page is sent to the client and page properties, such as Response
and Request, are unloaded and all cleanup done.

6.3 Life cycle events of ASP.NET page


Page life cycle events are as follows:
PreInit : PreInit is the first event in page life cycle. It checks the IsPostBack property and
determines whether the page is a postback. It sets the themes and master pages,
creates dynamic controls, and gets and sets profile property values. This event can be
handled by overloading the OnPreInit method or creating a Page_PreInit handler.
Init : Init event initializes the control property and the control tree is built. This event
can be handled by overloading the OnInit method or creating a Page_Init handler.
InitComplete : InitComplete event allows tracking of view state. All the controls turn on
view-state tracking.
7

LoadViewState : LoadViewState event allows loading view state information into the
controls.
LoadPostData : During this phase, the contents of all the input fields are defined with
the <form> tag are processed.
PreLoad : PreLoad occurs before the post back data is loaded in the controls. This event
can be handled by overloading the OnPreLoad method or creating a Page_PreLoad
handler.
Load : The Load event is raised for the page first and then recursively for all child
controls. The controls in the control tree are created. This event can be handled by
overloading the OnLoad method or creating a Page_Load handler.
LoadComplete : The loading process is completed, control event handlers are run, and
page validation takes place. This event can be handled by overloading the
OnLoadComplete method or creating a Page_LoadComplete handler
PreRender : The PreRender event occurs just before the output is rendered. By handling
this event, pages and controls can perform any updates before the output is rendered.
PreRenderComplete : As the PreRender event is recursively fired for all child controls,
this event ensures the completion of the pre-rendering phase.
SaveStateComplete : State of control on the page is saved. Personalization, control state
and view state information is saved. The HTML markup is generated. This stage can be
handled by overriding the Render method or creating a Page_Render handler.
UnLoad : The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad
event for all controls recursively and lastly for the page itself. Final cleanup is done and
all resources and references, such as database connections, are freed. This event can be
handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

7 Introduction to Web Forms


Web Forms are the User Interface(UI) elements that give the Web Applications their look and
feel. Web Forms have the following advantages.
Separation of HTML interface from application logic.
A set of server-side controls that can detect the browser and send out appropriate
markup language such as HTML.
Less code to write due to the data binding capabilities of the new server-side .NET
controls.
Event-based programming model that is familiar to Microsoft Visual Basic programmers.
Compiled code and support for multiple languages, as opposed to ASP which was
interpreted as Microsoft Visual Basic Scripting (VBScript) or Microsoft Jscript.
Allows third party to create controls that provide additional functionality.

In Web Forms, all server controls must appear within a <form> tag, and the <form> tag must
contain the runat="server" attribute. The runat="server" attribute indicates that the form
should be processed on the server. It also indicates that the enclosed controls can be accessed
by server scripts.

7.1 Sample Application


So now lets begin by developing a sample web application. Follow the steps given below.
1. Open Visual Studio 2015. Go to File menu -> New -> Project -> Web -> ASP.NET Web
Application and click OK. Select the template called Web Forms and click OK.
2. We will be developing a basic application hence we dont need Site.Master. Open
Solution Explorer, right click on Site.Master and delete it. If Solution Explorer is not
present then go to View menu and click on Solution Explorer to open it.

3. Now open Default.aspx from Solution Explorer and update it by modifying the code.
Copy only the highlighted code. Do not change the Page section from your code.
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._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>
<p>Jaqen H'ghar: What's your name?</p>
You:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="TextBox1" runat="server" style="width:224px">
</asp:TextBox>

<br />
<br />

<asp:Button ID="Button1" runat="server" Text="Reply"


style="width:85px" onclick="Button1_Click" />

<br />
<br />

10

<span runat="server" id="response" />


</div>
</form>
</body>

</html>

4. After copying the above code, open Default.aspx.cs and copy the following code inside
public partial class _Default : Page.
protected void Button1_Click(object sender, EventArgs e)
{
string buf = "Jaqen H'ghar: Valar Morghulis " + TextBox1.Text + "!";
response.InnerHtml = buf;
}

5. Now execute the application by clicking on Start(Can also be your default browser
name).

Note : This was an example of external scripting. You can also write the Button1_Click function
in Default.aspx by using <script> tag as shown below.
<script runat="server">
protected void Button1_Click(object sender, EventArgs e) {
string buf = "Jaqen H'ghar: Valar Morghulis " + TextBox1.Text + "!";
response.InnerHtml = buf;
}
</script>

11

8 Controls and Events


In ASP.NET, events raised at the client-side, and handled at the server-side. For example, a user
clicks a button displayed in the browser. A Click event is raised. The browser handles this clientside event by posting it to the server.

8.1 Web Server Controls


Web server controls are special ASP.NET tags known to the server. Web server controls are
created on the server and they require a runat="server" attribute to work.
<asp:control_name id="my_id" runat="server" />

In our sample application we have used Button server control along with an event handler for
the Click event.

8.2 Event Arguments


The general syntax of an event is:
private void Event_Name (object sender, EventArgs e);

In ASP.NET, event handlers generally take two parameters and return void. The first parameter
represents the object calling the event and the second parameter is event argument.

12

8.3 Textbox control


The TextBox control is used to create a text box. It is similar to normal HTML textbox. The only
difference is its attributes can be changed from the server-side and can also be used as an
event handler.
<form runat="server">

A basic TextBox:
<asp:TextBox id="tb1" runat="server" />
<br><br>

A password TextBox:
<asp:TextBox id="tb2" TextMode="password" runat="server" />
<br><br>

A TextBox with text:


<asp:TextBox id="tb3" Text="Hello World!" runat="server" />
<br><br>

A multiline TextBox:
<asp:TextBox id="tb4" TextMode="multiline" runat="server" />
<br><br>

A TextBox with height:


<asp:TextBox id="tb5" rows="5" TextMode="multiline" runat="server" />
<br><br>

A TextBox with width:


<asp:TextBox id="tb6" columns="30" runat="server" />

</form>

13

8.4 Button control


A Button control is generally used for event handling. Events are triggered when a user
performs a certain action. Events handlers are used for handling these events. They are coded
to respond to a particular action.
Eg.
<asp:Button ID="save" runat="server" Text="Save" />
<script>
Protected Sub save_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles save.Click
End Sub
</script>

Another way is the one we used in our sample application.


<asp:Button ID="Button1" runat="server" Text="Reply"
style="width:85px" onclick="Button1_Click" />
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
string buf = "Jaqen H'ghar: Valar Morghulis " + TextBox1.Text + "!";
response.InnerHtml = buf;
}
</script>

14

9 Data Binding
Data binding is used to fill lists with selectable items from database, an XML file, or a script.
Controls which support data binding are:

asp:RadioButtonList

asp:CheckBoxList

asp:DropDownList

asp:Listbox

9.1 Data binding to an ArrayList


First we need to create an ArrayList. Add() method is used to add items to the ArrayList and
Sort() method is used to sort them.
Try out this example.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
var arr = new ArrayList();
arr.Add("Sandwich");
arr.Add("Burger");
arr.Add("Hotdog");
arr.Add("Pizza");
arr.Add("Ice cream");
arr.Add("Coke");
arr.TrimToSize();
arr.Sort();
radiobtn.DataSource = arr;

15

radiobtn.DataBind();
}
}

protected void radiobtn_Event(object sender, EventArgs e)


{
lbl.Text = "Your order for "
+ radiobtn.SelectedItem.Text + " is placed.";
}
</script>

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

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

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

<asp:RadioButtonList
id="radiobtn"
AutoPostBack="true"
OnSelectedIndexChanged="radiobtn_Event"
runat="server"></asp:RadioButtonList>
<br />
<br />
<p><asp:Label id="lbl" runat="server"></asp:Label></p>
</form>
</body>
</html>

16

Some new things:


Page_Load Event : The Page_Load event is triggered when a page loads, and ASP.NET
will automatically call the subroutine Page_Load, and execute the code inside it.
Page.IsPostBack Property : The Page_Load subroutine runs every time the page is
loaded. To execute the code in the Page_Load subroutine only the first time the page is
loaded, the Page.IsPostBack property is used. If the Page.IsPostBack property is false,
the page is loaded for the first time, if it is true, the page is posted back to the server.
TrimToSize() method : This method is used to size an ArrayList to its final size.
DataSource property : It is a property of RadioButtonList control. Here it is set to
ArrayList and defines the data source of the RadioButtonList control.
DataBind() method : This method of the RadioButtonList control binds the data source
with the RadioButtonList control.

9.2 Data binding to Hashtable


The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very
quick searches can be made for values by searching through their keys.
Just like ArrayList, Add() method is used to add items to Hashtable.
Try out this example.
17

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


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

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
var hash = new Hashtable();
hash.Add("S", "Sandwich");
hash.Add("B", "Burger");
hash.Add("H", "Hotdog");
hash.Add("P", "Pizza");
hash.Add("I", "Ice cream");
hash.Add("C", "Coke");
radiobtn.DataSource = hash;
radiobtn.DataValueField = "Key";
radiobtn.DataTextField = "Value";
radiobtn.DataBind();
}
}

protected void radiobtn_Event(object sender, EventArgs e)


{
lbl.Text = "Your order for "
+ radiobtn.SelectedItem.Text + " is placed.";
}
</script>

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

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

18

</head>

<body>

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

<asp:RadioButtonList
id="radiobtn"
AutoPostBack="true"
OnSelectedIndexChanged="radiobtn_Event"
runat="server"></asp:RadioButtonList>

<br />
<br />

<p><asp:Label id="lbl" runat="server"></asp:Label></p>


</form>

</body>

</html>

19

9.3 Data binding to SortedList


The SortedList object contains items in key/value pairs. A SortedList object automatically sorts
the items in alphabetic or numeric order.
Add() method is used to add items to SortedList. A SortedList can be sized to its final size with
the TrimToSize() method.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
var sortlist = new SortedList();
sortlist.Add("S", "Sandwich");
sortlist.Add("B", "Burger");
sortlist.Add("H", "Hotdog");
sortlist.Add("P", "Pizza");
sortlist.Add("I", "Ice cream");
sortlist.Add("C", "Coke");
radiobtn.DataSource = sortlist;
radiobtn.DataValueField = "Key";
radiobtn.DataTextField = "Value";
radiobtn.DataBind();
}
}

protected void radiobtn_Event(object sender, EventArgs e)


{
lbl.Text = "Your order for "
+ radiobtn.SelectedItem.Text + " is placed.";
}
</script>

20

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

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

<body>

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

<asp:RadioButtonList
id="radiobtn"
AutoPostBack="true"
OnSelectedIndexChanged="radiobtn_Event"
runat="server"></asp:RadioButtonList>

<br />
<br />

<p><asp:Label id="lbl" runat="server"></asp:Label></p>


</form>

</body>
</html>

21

9.4 Data binding to XML file


Lets first create an XML file. Follow the steps given below.
1. Open Solution Explorer (Ctrl + Alt + L)
2. Right click on your web application name (Project name) and go to Add -> New item.
3. Go to Visual C# -> Data in the list on left side.
4. Click on XML File and rename it as TodaysMenu.xml.
5. Copy the following code in TodaysMenu.xml.
<?xml version="1.0" encoding="utf-8" ?>

<menulist>

<menu>
<text>Sandwich</text>
<value>S</value>
</menu>

<menu>
<text>Burger</text>

22

<value>B</value>
</menu>

<menu>
<text>Hotdog</text>
<value>H</value>
</menu>

<menu>
<text>Pizza</text>
<value>P</value>
</menu>

<menu>
<text>Ice cream</text>
<value>I</value>
</menu>

<menu>
<text>Coke</text>
<value>C</value>
</menu>

</menulist>

6. Save the code.

We need to import the System.Data namespace in Default.aspx.


<%@ Import Namespace="System.Data" %>

We also create a DataSet object and load the XML file into the DataSet when the page is first
loaded.
Copy this code in Default.aspx.

23

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


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

<%@ Import Namespace="System.Data" %>

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
var dset = new DataSet();
dset.ReadXml(MapPath("TodaysMenu.xml"));
radiobtn.DataSource = dset;
radiobtn.DataValueField = "value";
radiobtn.DataTextField = "text";
radiobtn.DataBind();
}
}

protected void radiobtn_Event(object sender, EventArgs e)


{
lbl.Text = "Your order for "
+ radiobtn.SelectedItem.Text + " is placed.";
}
</script>

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

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

24

<body>

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

<asp:RadioButtonList
id="radiobtn"
AutoPostBack="true"
OnSelectedIndexChanged="radiobtn_Event"
runat="server"></asp:RadioButtonList>

<br />
<br />

<p><asp:Label id="lbl" runat="server"></asp:Label></p>


</form>

</body>
</html>

25

10 DataList Control
The DataList control is used to display a repeated list of items that are bound to the control. It
adds a table around the data items by default. The DataList control may be bound to a database
table, an XML file, or another list of items.
Lets first create an XML File. Create a new XML File refering to the steps given in topic 9.4 and
rename it mobile.xml.
Copy this code in mobile.xml.
<?xml version="1.0" encoding="utf-8" ?>

<mobileList>

<mobile>
<company>Apple</company>
<model>iPhone 5s</model>
<release>September 2013</release>
<os>IOS</os>
</mobile>
<mobile>
<company>LG</company>
<model>Nexus 5</model>
<release>October 2013</release>
<os>Android</os>
</mobile>
<mobile>
<company>Moto</company>
<model>Nexus 6</model>
<release>November 2014</release>
<os>Android</os>
</mobile>
<mobile>
<company>Apple</company>
<model>iPhone 6s</model>

26

<release>September 2015</release>
<os>IOS</os>
</mobile>
<mobile>
<company>Huawei</company>
<model>Nexus 6P</model>
<release>September 2015</release>
<os>Android</os>
</mobile>
<mobile>
<company>LG</company>
<model>Nexus 5X</model>
<release>October 2015</release>
<os>Android</os>
</mobile>

</mobileList>

Now open Default.aspx and replace it with this code.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%@ Import Namespace="System.Data" %>

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
var dset = new DataSet();
dset.ReadXml(MapPath("mobile.xml"));
mobile.DataSource = dset;
mobile.DataBind();
}

27

</script>

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

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

<body>

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

<asp:DataList id="mobile" GridLines="Both" runat="server">

<HeaderTemplate>
High End Mobiles
</HeaderTemplate>

<ItemTemplate>
<%# Eval("company")%>
<%# Eval("model")%>
was released on
<%# Eval("release")%>
. Its OS is
<%# Eval("os")%>.
</ItemTemplate>

<FooterTemplate>
That's all guys!

28

</FooterTemplate>

</asp:DataList>

</form>

</body>

</html>

Here, we create a DataList control. The contents of the <HeaderTemplate> element are
rendered first and only once within the output, then the contents of the <ItemTemplate>
element are repeated for each "record" in the DataSet, and last, the contents of the
<FooterTemplate> element are rendered once within the output.
We add the script that creates the DataSet and binds the dset DataSet to the DataList control.
We also fill the DataList control with a <HeaderTemplate> that contains the header of the table,
an <ItemTemplate> that contains the data items to display, and a <FooterTemplate> that
contains a ending text.

29

11 Master Pages
Master pages allow us to create a template with a consistent look and behavior for all the pages
in your web application. A master page provides a template for other pages, with shared layout
and functionality. It 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 pages contain the content we want to display. When users request the content
page, ASP.NET merges the pages to produce output that combines the layout of the master
page with the content of the content page.
Lets see an example:
1. Open Solution Explorer. Right click on project (Project name) and go to Add -> New
item.
2. Go to Visual C# -> Web -> Web Forms and click on Web Forms Master Page and click OK.
3. Open the Master Page and copy this code in it.
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div style="background-color:cyan">
<h1>StudyLeague</h1>
<h3>We are Master Page Headers!</h3>
</div>

<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

30

</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

4. Save this file.


5. Now open Default.aspx and add MasterPageFile=Master_page_file_name attribute in
Page section.
6. Modify the code in Default.aspx.
<%@ Page Title="Home Page" Language="C#"
AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1._Default"
MasterPageFile="~/Site.Master"
%>

<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

<p>Nothing special here. We are normal people(text) from


Default.aspx</p>

</asp:Content>

7. Execute the web application.

Some important points:


The @ Master directive defines it as a master page.
31

The master page contains a placeholder tag <asp:ContentPlaceHolder> for individual


content.
The id="ContentPlaceHolder1" attribute identifies the placeholder, allowing many
placeholders in the same master page.
The @ Page directive defines it as a standard content page.
The content page contains a content tag <asp:Content> with a reference to the master
page (using id).

12 Navigation
ASP.NET has built-in navigation controls.
The Sitemap File is used to store menu. In addition to it, ASP.NET has three new navigation
controls:
Dynamic menus
TreeViews
Site Map Path

12.1 The Sitemap File


Rules for creating a sitemap file:
The XML file must contain a <siteMap> tag surrounding the content.
The <siteMap> tag can only have one <siteMapNode> child node.
Each <siteMapNode> can have several child nodes (web pages).
Each <siteMapNode> has attributes defining page title and URL.
So lets first create a sitemap file and then we will try all the three controls listed above with this
sitemap file:
1. Open Solution Explorer, right click on project, Add -> New item.
2. Go to Visual C# -> Web and click on Site Map. Do not rename the file.
3. Copy this code inside Web.sitemap.
32

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


<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="http://www.studyleague.com/dashboard.aspx" title="Home"
description="">
<siteMapNode url="http://studyleague.com/BrowseSubjects.aspx"
title="Available Contents"

description="">

<siteMapNode url="http://www.studyleague.com/SubjectsDetails.aspx?view=38"
title="Web programming"

description="" />

</siteMapNode>
</siteMapNode>
</siteMap>

12.2 Dynamic Menu:


<asp:Menu> control is used to display a standard site navigation menu. The <asp:Menu>
control is the placeholder for a server created navigation menu. The data source of the control
is defined by the DataSourceId attribute. The id="nav" connects it to the
<asp:SiteMapDataSource> control. The <asp:SiteMapDataSource> control automatically
connects to the default sitemap file (web.sitemap).
Modify your Default.aspx with this code and execute to see Dynamic menu. Remove the Master
page reference as we dont need it now(MasterPageFile attribute).
<%@ Page Title="Home Page" Language="C#"
AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1._Default"
%>

<!DOCTYPE html>

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

33

</head>
<body>
<asp:SiteMapDataSource id="nav" runat="server" />

<form runat="server">
<asp:Menu runat="server" DataSourceID="nav"></asp:Menu>
</form>
</body>
</html>

12.3 TreeView
<asp:TreeView> control is used to display a multi level navigation menu. The menu looks like a
tree with branches that can be opened or closed with + or - symbol. It is a placeholder for a
server created navigation menu. The data source of the control is defined by the DataSourceId
attribute. The id="nav" connects it to the <asp:SiteMapDataSource> control. The
<asp:SiteMapDataSource> control automatically connects to the default sitemap file
(web.sitemap).
Modify your Default.aspx with this code and execute to see TreeView. Remove the Master page
reference as we dont need it now(MasterPageFile attribute).
<%@ Page Title="Home Page" Language="C#"
AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1._Default"
%>

<!DOCTYPE html>

<html>

34

<head runat="server">
<title>Home Page</title>
</head>
<body>
<asp:SiteMapDataSource id="nav" runat="server" />

<form runat="server">
<asp:TreeView runat="server" DataSourceID="nav"></asp:TreeView>
</form>
</body>
</html>

12.4 SiteMapPath
The SiteMapPath control is used to display the trail (navigation path) to the current page. The
path acts as clickable links to previous pages. Unlike the TreeView and Menu control the
SiteMapPath control does not use a SiteMapDataSource. The SiteMapPath control uses the
web.sitemap file by default. It is a placeholder for a server created site path display.
Modify your Default.aspx with this code and execute to see SiteMapPath. Remove the Master
page reference as we dont need it now(MasterPageFile attribute).
<%@ Page Title="Home Page" Language="C#"
AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1._Default"
%>

<!DOCTYPE html>

35

<html>
<head runat="server">
<title>Home Page</title>
</head>
<body>

<form runat="server">
<asp:SiteMapPath runat="server"></asp:SiteMapPath>
</form>
</body>
</html>

13 Validation Controls
Validation controls are used to validate the values that are entered into other controls of a
page. They do both client-side validation and server-side validation. If the user input does not
pass validation, it will display an error message to the user.

The RangeValidator control verifies that the input value falls within a predetermined range.
<!DOCTYPE html>

<html>
<head runat="server">
<title>Home Page</title>
</head>
<body>

<form runat="server">
Enter a number between 10 and 100:<br />
<asp:TextBox id="textbox1" runat="server"></asp:TextBox>
<br /><br />

36

<asp:Button runat="server" Text="Submit" />


<asp:RangeValidator
runat="server" ControlToValidate="textbox1"
MinimumValue="10" MaximumValue="100" Type="Integer"
Text="Enter a value between 10 and 100" ></asp:RangeValidator>
</form>
</body>
</html>

37

You might also like