Professional Documents
Culture Documents
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
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.
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
Web.config
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.
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.
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.
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.
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" %>
<body>
<br />
<br />
<br />
<br />
10
</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
In our sample application we have used Button server control along with an event handler for
the Click event.
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
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 multiline TextBox:
<asp:TextBox id="tb4" TextMode="multiline" runat="server" />
<br><br>
</form>
13
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
<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();
}
}
<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
<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();
}
}
<head runat="server">
<title>
Untitled Page
</title>
18
</head>
<body>
<asp:RadioButtonList
id="radiobtn"
AutoPostBack="true"
OnSelectedIndexChanged="radiobtn_Event"
runat="server"></asp:RadioButtonList>
<br />
<br />
</body>
</html>
19
<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();
}
}
20
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<asp:RadioButtonList
id="radiobtn"
AutoPostBack="true"
OnSelectedIndexChanged="radiobtn_Event"
runat="server"></asp:RadioButtonList>
<br />
<br />
</body>
</html>
21
<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>
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
<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();
}
}
<head runat="server">
<title>
Untitled Page
</title>
</head>
24
<body>
<asp:RadioButtonList
id="radiobtn"
AutoPostBack="true"
OnSelectedIndexChanged="radiobtn_Event"
runat="server"></asp:RadioButtonList>
<br />
<br />
</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>
<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>
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<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>
</asp:Content>
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
description="">
<siteMapNode url="http://www.studyleague.com/SubjectsDetails.aspx?view=38"
title="Web programming"
description="" />
</siteMapNode>
</siteMapNode>
</siteMap>
<!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
37