You are on page 1of 66

ASP.

NET Web Forms Code


Framework Development

Rakesh Singh
NARESH I TECHNOLOGIES Hyderabad
0

ASP.NET Web Application Development Using Web Forms Code


Framework in Visual Studio IDE:
Using Visual Studio, you can create ASP.NET Web Forms. The Visual Studio Integrated Development
Environment (IDE) lets you drag and drop server controls to lay out your Web Forms page. You can then
easily set properties, methods, and events for controls on the page or for the page itself. These properties,
methods, and events are used to define the web page's behaviour, look and feel, and so on. To write server
code to handle the logic for the page, you can use a .NET language like Visual Basic or C#.
ASP.NET Web Forms are:

Based on Microsoft ASP.NET technology, in which code that runs on the server dynamically
generates Web page output to the browser or client device.

Compatible with any browser or mobile device. An ASP.NET Web page automatically renders the
correct browser-compliant HTML for features such as styles, layout, and so on.

Compatible with any language supported by the .NET common language runtime, such as
Microsoft Visual Basic and Microsoft Visual C#.

Built on the Microsoft .NET Framework. This provides all the benefits of the framework, including
a managed environment, type safety, and inheritance.

Flexible because you can add user-created and third party controls to them.

ASP.NET Web Forms offer:

Separation of HTML and other UI code from application logic.

A rich suite of server controls for common tasks, including data access.

Powerful data binding, with great tool support.

Support for client-side scripting that executes in the browser.

Support for a variety of other capabilities, including routing, security, performance,


internationalization, testing, debugging, error handling and state management.

ASP.NET Web Forms Helps You Overcome Challenges


Web application programming presents challenges that do not typically arise when programming traditional
client-based applications. Among the challenges are:

Implementing a rich Web user interface - It can be difficult and tedious to design and
implement a user interface using basic HTML facilities, especially if the page has a complex
layout, a large amount of dynamic content, and full-featured user-interactive objects.
Separation of client and server - In a Web application, the client (browser) and server are
different programs often running on different computers (and even on different operating
systems). Consequently, the two halves of the application share very little information; they can
communicate, but typically exchange only small chunks of simple information.
Stateless execution - When a Web server receives a request for a page, it finds the page,
processes it, sends it to the browser, and then discards all page information. If the user requests
the same page again, the server repeats the entire sequence, reprocessing the page from
scratch. Put another way, a server has no memory of pages that it has processedpage are
Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.

Page |1

stateless. Therefore, if an application needs to maintain information about a page, its stateless

nature can become a problem.


Unknown client capabilities - In many cases, Web applications are accessible to many users
using different browsers. Browsers have different capabilities, making it difficult to create an

application that will run equally well on all of them.


Complications with data access - Reading from and writing to a data source in traditional

Web applications can be complicated and resource-intensive.


Complications with scalability - In many cases Web applications designed with existing
methods fail to meet scalability goals due to the lack of compatibility between the various
components of the application. This is often a common failure point for applications under a
heavy growth cycle.

Meeting these challenges for Web applications can require substantial time and effort. ASP.NET Web Forms
and the ASP.NET framework address these challenges in the following ways:

Intuitive, consistent object model - The ASP.NET page framework presents an object model
that enables you to think of your forms as a unit, not as separate client and server pieces. In
this model, you can program the page in a more intuitive way than in traditional Web
applications, including the ability to set properties for page elements and respond to events. In
addition, ASP.NET server controls are an abstraction from the physical contents of an HTML page
and from the direct interaction between browser and server. In general, you can use server
controls the way you might work with controls in a client application and not have to think about
how to create the HTML to present and process the controls and their contents.
Event-driven programming model - ASP.NET Web Forms bring to Web applications the
familiar model of writing event handlers for events that occur on either the client or server. The
ASP.NET page framework abstracts this model in such a way that the underlying mechanism of
capturing an event on the client, transmitting it to the server, and calling the appropriate method
is all automatic and invisible to you. The result is a clear, easily written code structure that
supports event-driven development.
Intuitive state management - The ASP.NET page framework automatically handles the task
of maintaining the state of your page and its controls, and it provides you with explicit ways to
maintain the state of application-specific information. This is accomplished without heavy use of
server resources and can be implemented with or without sending cookies to the browser.
Browser-independent applications - The ASP.NET page framework enables you to create
all application logic on the server, eliminating the need to explicitly code for differences in
browsers. However, it still enables you to take advantage of browser-specific features by writing
client-side code to provide improved performance and a richer client experience.
.NET Framework common language runtime support - The ASP.NET page framework is
built on the .NET Framework, so the entire framework is available to any ASP.NET application.
Your applications can be written in any language that is compatible that is with the runtime. In
addition, data access is simplified using the data access infrastructure provided by the .NET
Framework, including ADO.NET.
Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.

Page |2

.NET Framework scalable server performance - The ASP.NET page framework enables
you to scale your Web application from one computer with a single processor to a multi-computer
Web farm cleanly and without complicated changes to the application's logic.

Deciding When to Create a Web Forms Application:


You must consider carefully whether to implement a Web application by using either the ASP.NET Web
Forms model or another model, such as the ASP.NET MVC framework. The MVC framework does not replace
the Web Forms model; you can use either framework for Web applications. Before you decide to use the
Web Forms model or the MVC framework for a specific Web site, evaluate the advantages of each approach.

Advantages of a Web Forms-Based Web Application:


The Web Forms-based framework offers the following advantages:

It supports an event model that preserves state over HTTP, which benefits line-of-business Web
application development. The Web Forms-based application provides dozens of events that are
supported in hundreds of server controls.

It uses a Page Controller pattern that adds functionality to individual pages.

It uses view state or server-based forms, which can make managing state information easier.

It works well for small teams of Web developers and designers who want to take advantage of
the large number of components available for rapid application development.

In general, it is less complex for application development, because the components


(the Page class, controls, and so on) are tightly integrated and usually require less code than
the MVC model.

Advantages of an MVC-Based Web Application:

The ASP.NET MVC framework offers the following advantages:

It makes it easier to manage complexity by dividing an application into the model, the view, and
the controller.

It does not use view state or server-based forms. This makes the MVC framework ideal for
developers who want full control over the behaviour of an application.

It uses a Front Controller pattern that processes Web application requests through a single
controller. This enables you to design an application that supports a rich routing infrastructure.

It provides better support for test-driven development (TDD).

It works well for Web applications that are supported by large teams of developers and Web
designers who need a high degree of control over the application behaviour.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |3

Creating a first ASP.Net Sample Web Site with C# Using Plain Text Editor i.e.
Notepad environment with following resources and setup this website in IIS or
you can say that required to host a website on a given web server i.e. IIS.

For Example:
D:\ - Physical Location on the Server Machine
SampleWebSite Website Folder
Images - Folder
Ads1.jpg

Image Used in Web Form

Web Form - UI
Default.aspx
Default.aspx.cs
Web Form Code File
Use the notepad text editor to create a web form (UI) file i.e. Default.aspx & Code File
i.e. Default.aspx.cs as following:
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>ASP.NET Web Site</title>
<script type="text/javascript">
function validate() {
var firstName = document.getElementById("TextBox1").value;
var lastName = document.getElementById("TextBox2").value;
var error = "";
if (firstName == "")
error += "Please Enter First Name" + "\n";
Client Side Script Code
if (lastName == "")
error += "Please Enter Last Name" + "\n";
if (error != "") {
alert(error);
return false;
}
}
</script>
</head>
<body style="background-color: Azure">
<form id="form1" runat="server">
<asp:Image ID="Image1" runat="server" ImageUrl="Images/Ads1.jpg" Width="99%"
Height="150" AlternateText="Image Control" ToolTip="Image Banner" BorderStyle="Dotted"
BorderWidth="5" BorderColor="Green" />
<marquee direction="right" style="background-color: yellow; color: green; font-size: 25px; border:
5px solid red">
<h1>Welcome to ASP.NET Web Site</h1>
</marquee>
<hr />

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |4

<asp:Label ID="Label1" runat="server" Text="Enter First Name: " Font-Size="15" Font-Bold="True"


ForeColor="Blue" />
<asp:TextBox ID="TextBox1" runat="server" />
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Enter Last Name: " Font-Size="15" FontBold="True" ForeColor="Blue" />
<asp:TextBox ID="TextBox2" runat="server" />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return validate();"
OnClick="Button1_Click" />
<br />
<asp:Label ID="Label3" runat="server" />
</form>
</body>
</html>

Default.aspx.cs (Code File):


using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;

public partial class Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Focus();
}

Server Side Script Code

protected void Button1_Click(object sender, EventArgs e)


{
string firstName = TextBox1.Text.Trim();
string lastName = TextBox2.Text.Trim();
string fullName = firstName + " " + lastName;
Label3.Text="<b>Your Name Is: </b>" + fullName;
}

Once The Website is ready with their resources as shown above, You required to
Host or setup a website on a given web server i.e. IIS
Hosting a Web Site to an IIS Web Server:
These are following steps to host or setup a Website to an IIS Webserver:
1. Open IIS Manger
2. To setup a new website in IIS, expand Server (Machine Name) -> Sites -> Default Web Site
Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.
Page |5

3. Right-Click on Default Web Site and choose Add Application and enter the details as
following:

Click OK to complete hosting or setup a new website to an IIS Webserver.

Once a Website is hosted on IIS Web Server, It can be accessed from the same machine or any
other client machine in the same network by making request to Webserver using Browser Interface
as following:
1. Open Any Web Browser
2. Type the following URL:
From The Same Machine:
http://localhost/SampleWebSite/Default.aspx
OR
http://MachineName/SampleWebSite/ Default.aspx
From Any Other Client Machine in the Same Network:
http://ServerMachineName/SampleWebSite/ Default.aspx
Or
http://IP Address/SampleWebSite/ Default.aspx

Output:

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |6

Creating First ASP.NET Website with Visual C# Programming


Language in Visual Studio IDE (Integrated Development
Environment):In Order to create an ASP.NET Web Application follow these steps:
Steps to Create ASP.Net Web Application:1. Open Visual Studio 2010/2012/2013
2. Click on Main Menu i.e. File->New->Web Site, It Opens Automatically "New Web Site Templates
Window"
3. Select "ASP.Net Empty Web Site" from Templates Section
4. Select appropriate .Net Framework Version such as 4.5.1/4.5/4.0/3.5/3.0/2.0 from top of
Window.
5. Select Language as "Visual C#" or "Visual Basic"
6. Select Location as "File System" or "HTTP" or "FTP", and Specify the Web Site Name with
Specified path
7. Finally Click Ok Button.
After Clicking Ok button, it creates automatically New Empty Web Site with following Contents
(Items):
1. Web.config (Applications Configuration File)

Types of Web Site Project Creation in Visual Studio IDE:


Describes different methods Visual Studio can use to access files for Web site
projects.
Visual Studio can access the files of a Web site project directly in a computer's file system,
through IIS on the local computer or a remote computer, or through FTP on a remote
computer. The names of Web site project types identify the method used: file-system
sites, local or remote IIS sites, and File Transfer Protocol (FTP)deployed sites.
OR
It describes how files are stored on your Web site, using either file-system based Web
sites or those that require Internet Information Services (IIS).
You can use Visual Studio to create and work with ASP.NET Web sites (which are also
known as Web applications) in a variety of configurations:
1. File-System Sites,
2. HTTP (Local IIS Sites)
3. FTP (File Transfer Protocol) Sites.
Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.
Page |7

File-System Web Site Projects:


In a file-system Web site project, you can create and edit files in any folder, whether on your local computer
or in a folder on another computer that you access over a network. You are not required to run IIS on your
computer. Instead, you can test pages by using the Visual Studio Development Server.
You can create a file-system Web site project and later create an IIS virtual directory that points to the
folder containing your pages.

Web Servers in Visual Studio for ASP.NET Web Projects:


When you develop web projects in Visual Studio, you need a web server to test or run them. Visual Studio
lets you test with different web servers, including IIS Express, Internet Information Services (IIS),
External Hosts, or Custom Web Servers. You can use any of these web servers with a file-based web
application project. For a file-based web site project, you can use IIS Express.
The following table provides summary guidance for choosing a web server in Visual Studio/Visual Web
Developer.
Web server

When to use

IIS Express

IIS Express is the default web server for web application projects in Visual Studio
2012 and Visual Studio 2013, and it is recommended for both web application
projects and web site projects.

Local IIS

Use IIS when you want to test your web application using the server environment
that is closest to what the live site will run under, and it is practical for you to install
and work with IIS on your development computer.
You can use IIS with web site projects, but not with web application projects.

External Host

You can specify the URL of an external host that you will use for testing.

Custom Web
Server

Visual Studio 2013 adds support for specifying custom Web servers in your projects;
this functionality enables developers to define the environment for testing their Web
applications.

IIS Express is designed to emulate IIS, but minor differences between IIS Express and the full version of
IIS may result in errors that occur only after you have deployed your website to a production version of
IIS. If you use IIS Express, it is recommended that you test your application on a staging server that uses
the target version of IIS before deploying it to a live site.
By default, Visual Studio 2012 and Visual Studio 2013 use IIS Express.

Using IIS Express with Visual Studio:


IIS Express includes many of the features of IIS 7 and IIS 8 web servers without requiring you to install
and manage IIS on your computer. Because IIS Express is similar to IIS 7 and IIS 8, it lets you transition
web sites to IIS more smoothly than using other Web servers.
IIS Express offers the following features:

It supports and enables the same extensibility model and Web.config file settings as IIS 7 and IIS 8.

It does not require changes in your web application code.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |8

It can be installed side-by-side with the full version of IIS and other web servers. You can choose a
different web server for each project.

In corporate environments, IIS Express offers the following features:

It does not require an administrator account in order to run or debug applications.

It does not serve requests to a browser on another computer, making its approval easier in corporate
environments.

It can be installed on versions of Windows that do not support IIS 7 or IIS 8.

Note: Although IIS Express is derived from IIS and supports the core features of IIS, there are some
differences between these servers.

Installing IIS Express:


IIS Express is installed automatically when you install Visual Studio 2012 and Visual Studio 2013. If you
want to install IIS Express in Visual Studio 2010 (SP1 is required), you can use the Microsoft Web Platform
Installer.

To install IIS Express

1. In a browser, go to the installation


page (http://www.microsoft.com/web/gallery/install.aspx?appid=IISExpress) of the
Microsoft.com/web site.
2. Download the installer and then follow the steps to finish the installation.

Using the IIS Express System Tray Application


IIS Express starts automatically when you run a project in Visual Studio, and it stops when you close the
web site project or web application project in Visual Studio. When IIS Express is running, it displays an
icon in the system tray, as shown in the following illustration.

The following table lists typical tasks for IIS Express and how to perform them.
Task

Steps

Display a list of all sites


that are running on IIS
Express

Right-click the IIS Express icon in the system tray, and then click Show All
Applications.

View
a
web
site
directory
location,
configuration path, and
.NET
Framework
version

Select the web site in the IIS Express window. The information will appear
beneath the list of web sites.

Stop IIS Express

Right-click the tray icon and select Exit.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |9

HTTP (Local IIS Sites):


You test local IIS Web site projects using a copy of IIS that is installed on your computer. When you create
a local IIS Web site project, the pages and folders for your site are stored in a folder under the default IIS
folder for Web sites, which is located at [drive]:\Inetpub\wwwroot. Visual Studio also creates the
appropriate IIS configuration so that the Web site is recognized by IIS as an application.

Note:
To create a local IIS Web site project, you need to have administrative privileges on the computer.
Alternatively, you can create an IIS virtual directory in Visual Studio. In that case, the pages and folders
for your Web site can be in any folder to which users have access, and a virtual directory in your local copy
of IIS must point to the file location.

Using IIS with Visual Studio:


The production web server for Microsoft operating systems is IIS, which can include a web server, File
Transfer Protocol (FTP) server, Simple Mail Transfer Protocol (SMTP) virtual email server, and other facilities.
In order to run IIS, you must be working with one of the versions of Windows that is listed in the following
table:

Windows Version

IIS version

Windows Server 2012 R2


Windows 8.1

IIS 8.5

Windows Server 2012


Windows 8

IIS 8.0

Windows Server 2008 R2


Windows 7 (Home Premium,
Professional, Enterprise, and
Ultimate editions)

IIS 7.5

Windows Server 2008


Windows Vista (Home Premium,
Business, Enterprise, and Ultimate
editions)

IIS 7.0

Windows Server 2003


Windows XP Professional x64

IIS 6.0

Windows XP Professional x32

IIS 5.1
Note: This version of IIS is not recommended; you should use
IIS Express if possible.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 10

Advantages of Using IIS as a Development Server with Visual Studio


Working directly with IIS as your development web server lets you work in an environment closer to that
of an IIS production web server. This can help you solve configuration problems before your project goes
live. If you use IIS Express, the transition to an IIS production web server might require you to perform
extra configuration tasks because of the different security contexts between test and production servers.

Disadvantages of Using IIS as a Development Web Server:


Using IIS as a development server can require more setup and configuration tasks in order to work with
Visual Studio than using IIS Express, including the following:
Both IIS and ASP.NET must be enabled in Windows, and ASP.NET must be registered with
Windows. (Registration is a separate step if you installed the .NET Framework first, and then
enabled IIS. Using ASP.NET IIS Registration Tool (Aspnet_regiis.exe).)
You must run Visual Studio as an administrator in order to work with IIS.
In addition, it might be impractical for you to work with IIS if any of the following apply:
Your corporate workplace policy does not allow server roles like IIS to be enabled on developer
computers.
Your corporate workplace policy does not allow developers to have administrator accounts on IIS.
You are developing ASP.NET web pages while working with a Home Edition of Windows, which does
not support IIS.
You do not want to host a web server on your computer (for example, on your home network) for
security reasons.
Your web project uses a SQL Server Express LocalDB database.
In this case you can use IIS Express.

Remote IIS Web Site Projects:


A remote Web site project uses IIS that is on another computer that you can access over a local area
network. The remote computer must have IIS installed and be configured with FrontPage Server
Extensions from Microsoft. When you create a remote Web site project, the pages and folders for your site
are stored under the default IIS folder on the remote computer. By default, this folder is located at
[drive]:\Inetpub\wwwroot. When you test pages in the project, they are served using IIS on the remote
computer.

FTP Web Site Projects


Visual Studio allows you to open and edit Web sites that are available on an FTP server. This is a typical
scenario if your Web site is located on a hosting site.
You can connect from within Visual Studio to any FTP server on which you have Read/Write permissions.
You can then create and edit Web pages on that server. If the FTP server is configured with ASP.NET and
an IIS virtual root that points to the FTP directory, you can also run your pages from the server to test
them.

Choosing a Web Site Project Type:


The following table summarizes the types of Web site projects that you can create in Visual Studio, which
you can use when deciding which type of Web site meets your needs.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 11

Web Site
Project Type

Summary

File-system
Web
site
project

Use a file-system Web site project when you want to create Web pages on your local
computer or on a shared drive and you do not have IIS installed. You can create a filesystem Web site and later create an IIS virtual directory that points to the folder
containing your pages.
Advantages
The site can be accessed only from the local computer, which reduces security
vulnerabilities.
You do not need to have IIS installed on your computer.
You do not need administrative rights to create or debug a local file-system Web
site.
If the computer is configured to allow remote desktop connections, multiple
users can create and debug local file-system Web sites at the same time.
Disadvantages
You cannot test a file-system Web site with IIS features, such as HTTP-based
authentication, application pooling, and ISAPI filters. There are also some
differences between the way the Visual Studio Development Server works and
the way IIS works. Therefore, you should test your project by running it with
IIS before deploying it to production.

Local IIS Web


site project

Use when you want to create Web pages on your local computer and you have IIS
installed.
Advantages
The site can be accessed from other computers if IIS is configured to make it
available to them.
You can test with IIS features, such as HTTP-based authentication, application
pooling, and ISAPI filters. You should test with IIS before you deploy to
production anyway due to differences between the Visual Web Development
Server and IIS. Therefore, testing in Visual Studio more accurately represents
how the site will behave in production (except that security is likely to be
different in test and production.)
Disadvantages
You must have administrative rights to create or debug an IIS Web site project.
Only one user on the computer can debug an IIS Web site project at one time.
By default, remote access is enabled for a local IIS Web site project.

Remote
Web
project

Use when you want to create a Web site by using IIS running on a remote computer.
The remote computer must be configured with FrontPage Server Extensions.
Advantages
You can test the Web site project on the server where it will be deployed.
Multiple developers can work with the same remote Web site project at the
same time.
Disadvantages
Configuration for debugging a remote Web site project is complex.

IIS
site

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 12

FTP Web
project

site

Only one developer can debug the remote Web site project at one time. All
other requests are suspended while the developer is stepping through code.

Use an FTP Web site project when your site already exists on a remote computer that
has been configured as an FTP server. (For example, your Internet service provider
(ISP) has provided space on a server.)
Advantages
You can test the FTP Web site project on the server where it will be deployed.
Disadvantages
You do not have local copies of the FTP Web site project files unless you copy
them yourself.
You cannot create an FTP Web site project you can only open one.
Typical file editing operations, such as opening and saving files, might be slow.
Because you are editing a live site, it is easier than with other Web project types
to introduce an error that users can see.

For Example:
1. Web Location: File System
Physical Path:
C:\Users\Rakesh\Documents\Visual Studio 2012\WebSites\WebSiteFileSystem1
2. Web Location: HTTP
Virtual Path:
http://localhost/WebSiteHttp
Physical Path:
C: /Inetpub/wwwroot/WebSiteHttp1
Once a web site is created by choosing "ASP.NET Empty Web Site" Template, It's created with following
contents:Web.config: Applications Configuration File
By Default Web.config (Applications Configuration File) containing configuration settings of an application
as following:
Web.config:
<?xml version="1.0"?>
<!-For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="false" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
</configuration>

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 13

Creating a New Web Form:


To create a new web form, Open solution explorer, right click application root, select Add -> Add New Item,
it opens automatically new window i.e. Add New Template, in which select Language as "Visual C#" at the
left side, and choose Template as "Web Form, and accept the default name i.e. "Default.aspx" or change it
as per need, and then finally click Add Button.
A Web Form will be created with following two files:Default.aspx -----> UI
Default.aspx.cs ------> Code
Note: By Default ASP.Net supports separation of UI and Code for any Web Form (.aspx page), it is called
"Code-Behind Model".
Default.aspx or we can say any of the Web Form by default created with following markup in the source
view:Skeleton Code:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Default.aspx.cs:
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
}
}
Note: ASP.NET Web Form Class in Code File must inherit from the System.Web.UI.Page Class.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 14

Visual Studio Templates for Web Projects:


Visual Studio includes project templates to help you get started when you create a web project. You can create web
application projects or web site projects. By considering the most appropriate project type before you begin, you can save
time when you create, test, and deploy the web project.

Web Project Templates:


From the File menu, you can select either New Project or New Web Site. The New Project dialog box provides a list of
web application templates. Use the web application project template to create web applications that are compiled into an
assembly and that provide rich options for deployment.
The New Web Site dialog box provides a list of web site templates. Use the Web Site project template when you want to
compile the source code dynamically.

Note:
You can install additional products by using the NuGet package manager. In some cases, these products include additional
templates for new projects. The lists in this topic show you only the templates that are included by default with Visual Studio
2012.

Web Application Templates:


Web application templates help you create a web project that is compiled into an assembly for deployment. The following
table lists templates that appear in the New Project dialog box under the Web category after you select a language (Visual
Basic or Visual C#).
Project Template

Information

ASP.NET Web
Forms Application

Use this project template to create a web application that is based on ASP.NET Web Forms pages
and that includes the following functionality.
A master page.
A cascading style sheet.
Login security that uses the ASP.NET membership system.
Ajax scripting that uses jQuery.
Navigation that uses a menu control.
By default, the ASP.NET Web Application project template includes the following:
Folders to contain membership pages, client script files, and cascading style sheet files.
A data folder (App_Data), which is granted permissions that allow ASP.NET to read and
write to it at run time.
A master page (the Site.master file).
Web pages named Default.aspx, Contact.aspx, and About.aspx. These content pages are
based on the default master.
A global application class (Global.asax file).
A Web.config file.
A Packages.config file.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 15

ASP.NET MVC 3
Web Application

Use this project template to create web applications that use a model-view-controller pattern,
using the ASP.NET MVC 3 release. The MVC pattern helps separate the different aspects of the
application (input logic, business logic, and UI logic), while providing a loose coupling between
these elements. In addition, this project template promotes test-driven development (TDD).

ASP.NET MVC 4
Web Application

Use this project template to create web applications that use a model-view-controller pattern,
using the ASP.NET MVC 4 release.

ASP.NET Empty
Web Application

This template creates an ASP.NET web application that includes a Web.config file, but no other
files. Use this project template when you do not require the functionality built into the standard
template.

ASP.NET Dynamic
Data Entities Web
Application

Use this project template to create a Dynamic Data web application that uses the ADO.NET Entity
Framework. This type of Dynamic Data web application can target any relational database.
Dynamic Data automatically generates a functional web application for viewing and editing data,
based on the schema of the data.

ASP.NET AJAX
Server Control

Use this project template to create a web server control for ASP.NET Web Forms pages that
incorporates Ajax functionality. The control consists of server and client code that work together
to produce rich client behaviour.

ASP.NET AJAX
Server Control
Extender

Use this project template to create an Ajax component that enhances the client capabilities of
standard ASP.NET web server controls.

ASP.NET Server
Control

Use this project template to create a custom ASP.NET web server control that can be used in
ASP.NET Web Forms pages.

Web Site Templates:


Web site templates help you create a web project that by default is compiled dynamically. The following table lists templates
that appear in the New Web Site dialog box.
Project Template

Information

ASP.NET Web Forms


Site

Use this project template to create a website that includes the following functionality:
A master page.
A cascading style sheet.
Login security that uses the ASP.NET membership system.
Ajax scripting that uses jQuery.
Navigation using a menu control.
By default, the ASP.NET Web Site project template includes the following:
Folders to contain membership pages, client script files, and cascading style sheet files.
A data folder (App_Data), which is granted permissions that allow ASP.NET to read and
write to it at run time.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 16

A master page (.master file).


Web pages named Default.aspx and About.aspx. In the project template, these pages
are content pages that use default master page.
A global application class (Global.asax file).
A Web.config file.

ASP.NET Web Site


(Razor v1)

Use this project template to create a website that uses ASP.NET Web Pages with the Razor syntax.

ASP.NET Web Site


(Razor v2)

Use this project template to create a website that uses ASP.NET Web Pages version 2 with Razor
syntax.

ASP.NET Empty Web


Site

This template creates an ASP.NET website that includes a Web.config file but no other files. Use
this project template when you do not require the functionality built into the standard.

ASP.NET Dynamic
Data Entities Web
Site

Use this project template to create a Dynamic Data website that uses the ADO.NET Entity
Framework. This type of Dynamic Data web application can target any relational database.
Dynamic Data automatically generates a functional web application for viewing and editing data,
based on the schema of the data.

WCF Service

Use this project template to create a Windows Communication Foundation (WCF) service. You
can extend the service so that a website, web application, Silverlight application, Ajax application,
or other client can call it.

ASP.NET Reports
Web Site

Use this project template to create an ASP.NET website that contains a report (.rdlc file), a default
ASP.NET Web Forms page (.aspx file) that contains a ReportViewer control, and a Web.config
file.

Web Application Projects versus Web Site Projects in Visual Studio:


In Visual Studio you can create web application projects or web site projects. You create or open a web application project
by choosing New Project or Open Project in the Visual Studio File menu. You create or open a web site project by
choosing New Web Site or Open Web Site in the File menu. Its best to choose the right type before you create a web
project, because it can be time-consuming, difficult, and error-prone to convert from one type to the other.

Note:
For new development, we recommend that you choose web application projects. This topic explains that web site projects
have some advantages, but many developers who choose web site projects eventually find that the disadvantages outweigh
any perceived advantages. In addition, as new ASP.NET features are developed, they wont always be made available for
web site projects. For example, the next Visual Studio release after Visual Studio 2012 will have new tooling for creating web
projects, and this new tooling will work only with web application projects.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 17

The following table summarizes the main differences:

Project file
structure

Compilation

Web application projects

Web site projects

A Visual Studio project file (.csproj or .vbproj)


stores information about the project, such as the
list of files that are included in the project, and any
project-to-project references.

There is no project file (.csproj or .vbproj). All the


files in a folder structure are automatically included
in the site.

You explicitly compile the source code on


the computer that is used for
development or source control.

By default, compilation of code files


(excluding .aspx and .ascx files) produces
a single assembly.

The source code is typically compiled


dynamically (automatically) by ASP.NET on
the server the first time a request is
received after the site has been installed or
updated.
You can precompile the site (compile in
advance on a development computer or on
the server).
By default, compilation produces multiple
assemblies.

Namespaces

Explicit namespaces are added to pages,


controls, and classes by default.

Explicit namespaces are not added to


pages, controls, and classes by default, but
you can add them manually.

Deployment

You copy the assembly to a server. The


assembly is produced by compiling the
application.

You copy the application source files to a


computer that has IIS installed on it.
If you precompile the site on a
development computer, you copy the
assemblies produced by compilation to
the IIS server.
Visual Studio provides tools that integrate
with Web Deploy (the IIS web deployment
tool) to automate many deployment tasks.

Visual Studio provides tools that


integrate with Web Deploy (the IIS web
deployment tool) to automate many
deployment tasks.

Note:
There is no difference in performance between a web site project and a web application project. The only significant
exceptions are the ones that have already been noted, and as a practical matter they apply only to very large sites. The first
request to the web site might require the site to be compiled, which can result in a delay. And if the web site is running on
an IIS server that is short on memory, including the entire site in a single assembly might use more memory than would be
required for multiple assemblies.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 18

The ASP.NET Page Structure Options:


ASP.NET provides two paths for structuring the code of our ASP.NET pages.
The first path utilizes the code-inline model. This model should be familiar to classic ASP 2.0/3.0 developers
because all the code is contained within a single .aspx page.
The second path uses ASP.NETs code-behind model, which allows for code separation of the pages business
logic from its presentation logic. In this model, the presentation logic for the page is stored in an .aspx
page, whereas the business logic piece is stored in a separate class file: .aspx.vb or .aspx.cs.
Using the code-behind model is considered the best practice because it provides a clean model in separation
of pure UI elements from code that manipulates these elements. It is also seen as a better means in
maintaining code.

Code Inline Model:


Inline Code refers to the code that is written inside an ASP.NET Web Page that has an extension of .aspx.
It allows the code to be written along with the HTML source code using a <script runat=server> tag. Its
major point is that since it's physically in the .aspx file it's deployed with the Web Form page whenever the
Web Page is deployed.
You can say, In-line code is code that is embedded directly within the ASP.NET page (.aspx page).
To build an ASP.NET page inline instead of using the code-behind model, we simply select the page type
from the Add New Item dialog and make sure that the Place Code in Separate File check box is not
selected. You can get at this dialog by right clicking the project or the solution in the Solution Explorer and
selecting Add -> Add New Item.
From here (Add New Item dialog), we can see the check box, we need to unselect if we want to build our
ASP.NET pages inline code model.
The following table shows the inline options when selecting files from this dialog:
Inline Coding File
Options
Web Form
Master Page
Web User Control
Web Services

Created File Extension


.aspx file
.master file
.ascx file
.asmx file

Example: The following code represents a simple page that uses the inline coding model:

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 19

Default.aspx:
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
txtValue1.Focus();
}
void Calc(string op)
{
lblStatus.Text = string.Empty;
txtResult.Text = string.Empty;
try
{
float value1 = float.Parse(txtValue1.Text.Trim());
float value2 = float.Parse(txtValue2.Text.Trim());
float result = 0;
switch (op)
{
case "+":
result = value1 + value2;
break;
case "-":
result = value1 - value2;
break;
case "*":
result = value1 * value2;
break;
case "/":
if (value2 == 0)
throw new DivideByZeroException("You can't divide by zero!!!");
result = value1 / value2;
break;
}
txtResult.Text = result.ToString();
}
catch (FormatException ex1)
{
lblStatus.Text = ex1.Message;
}
catch (OverflowException ex2)
{
lblStatus.Text = ex2.Message;
}
catch (DivideByZeroException ex3)
{
lblStatus.Text = ex3.Message;
}

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 20

}
protected void btnAdd_Click(object sender, EventArgs e)
{
Calc("+");
}
protected void btnSub_Click(object sender, EventArgs e)
{
Calc("-");
}
protected void btnMul_Click(object sender, EventArgs e)
{
Calc("*");
}
protected void btnDiv_Click(object sender, EventArgs e)
{
Calc("/");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function validate() {
var value1 = document.getElementById("txtValue1").value;
var value2 = document.getElementById("txtValue2").value;
var error = "";
if (value1 == "")
error += "Please Enter Value1" + "\n";
if (value2 == "")
error += "Please Enter Value2" + "\n";
if (error != "") {
alert(error);
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h1 style="text-align: center; color: maroon">Inline Code Model Example
</h1>
<div align="center">
<asp:Label ID="lblStatus" runat="server" ForeColor="Red" />
<br />
<br />
<b>Enter Value1:</b><asp:TextBox ID="txtValue1" runat="server" />
<br />
<br />

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 21

<b>Enter Value2:</b><asp:TextBox ID="txtValue2" runat="server" />


<br />
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClientClick="return validate();"
OnClick="btnAdd_Click" />
&nbsp;
<asp:Button ID="btnSub" runat="server" Text="Sub" OnClientClick="return validate();"
OnClick="btnSub_Click" />
&nbsp;
<asp:Button ID="btnMul" runat="server" Text="Mul" OnClientClick="return validate();"
OnClick="btnMul_Click" />
&nbsp;
<asp:Button ID="btnDiv" runat="server" Text="Div" OnClientClick="return validate();"
OnClick="btnDiv_Click" />
<br />
<br />
<b>Result:</b><asp:TextBox ID="txtResult" runat="server" ReadOnly="true" />
</div>
</form>
</body>
</html>
Note:
We can see that all the business logic is encapsulated in between <script runat=server> tags. The nice
feature of the inline model is that the business logic and the presentation logic are contained within the
same file. Some developers find that having everything in a single viewable instance makes working with
the ASP.NET page easier. Another great thing is that Visual Studio 2005 onwards provides IntelliSense when
working with the inline coding model. Before Visual Studio 2005, this capability did not exist. Visual Studio
.NET 2002/2003 forced you to use the code-behind model and, even if you fixed it so your pages were using
the inline model, you lost all IntelliSense capabilities.

Code-Behind Model:
Code Behind refers to the code for an ASP.NET Web page that is written in a separate class file that can
have the extension of .aspx.cs or .aspx.vb depending on the language used. Here the code is compiled into
a separate class from which the .aspx file derives. You can write the code in a separate .cs or .vb code file
for each .aspx page. One major point of Code Behind is that the code for all the Web pages is compiled into
a DLL file that allows the web pages to be hosted free from any Inline Server Code.
Code-behind Model refers to code for our ASP.NET page that is contained within a separate class file. This
allows a clean separation of our UI from our Code. To create a new page in our ASP.NET solution that uses
the code - behind model, to build a page that uses the code - behind model, we first select the page in the
Add New Item dialog and make sure the Place Code in Separate File check box is selected.
The following table shows the code-behind model options when selecting files from this dialog:
Code-Behind File
Options
Web Form
Master Page
Web User Control
Web Services

Created File Extension


.aspx file
.aspx.cs file or .aspx.vb file
.master file
.master.cs file or .master.vb file
.ascx file
.ascx.cs file or .ascx.vb file
.asmx file
.cs file or .vb file

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 22

The idea of using the code - behind model is to separate the business logic and presentation logic into
separate files. Doing this makes working with your pages easier, especially if you are working in a team
environment where visual designers work on the UI of the page and coders work on the business logic that
sits behind the presentation pieces.
Code Behind approach is a better way to develop and design the .aspx page having basic layout of a web
page containing all the necessary controls required for the GUI of the web page. Then include the C# or VB
code behind class file for handling the events of controls. This mechanism separates the web page from
design layout from the coding part.
Example:
Code - Behind model Sample Example:

Default2.aspx:
Source View:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function validate(v) {
if (v != "") {
document.getElementById("lblError").innerHTML = "";
var value1 = document.getElementById("txtValue1").value;
var value2 = document.getElementById("txtValue2").value;
var error = "";
if (value1 == "")
error += "Please Enter Value1" + "<br />";
if (value2 == "")
error += "Please Enter Value2" + "<br />";
if (error != "") {
document.getElementById("lblError").innerHTML = error;
return false;
}
else {
__doPostBack(event, "");
return true;
}
}

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 23

else {
document.getElementById("lblError").innerHTML = "Please Select Any Option!!!";
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h1 style="text-align: center; color: maroon">Code Behind Model Example</h1>
<div align="center">
<asp:Label ID="lblError" runat="server" ForeColor="Red" />
<br />
<br />
<b>Enter Value1:</b><asp:TextBox ID="txtValue1" runat="server" />
<br />
<br />
<b>Enter Value2:</b><asp:TextBox ID="txtValue2" runat="server" />
<br />
<br />
<b>Select Option:</b>
<asp:DropDownList ID="ddlCalc" runat="server" AutoPostBack="true" onchange="return
validate(this.value);" OnSelectedIndexChanged="ddlCalc_SelectedIndexChanged">
<asp:ListItem Text="Select" Value="" />
<asp:ListItem Text="Add" Value="+" />
<asp:ListItem Text="Sub" Value="-" />
<asp:ListItem Text="Mul" Value="*" />
<asp:ListItem Text="Div" Value="/" />
</asp:DropDownList>
<br />
<br />
<b>Result:</b><asp:TextBox ID="txtResult" runat="server" ReadOnly="true" />
</div>
</form>
</body>
</html>
Code File (Default2.aspx.cs):
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
txtValue1.Focus();
}
protected void ddlCalc_SelectedIndexChanged(object sender, EventArgs e)

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 24

{
lblError.Text = string.Empty;
txtResult.Text = string.Empty;
try
{
float value1 = float.Parse(txtValue1.Text.Trim());
float value2 = float.Parse(txtValue2.Text.Trim());
float result = 0;
switch (ddlCalc.SelectedItem.Value)
{
case "+":
result = value1 + value2;
break;
case "-":
result = value1 - value2;
break;
case "*":
result = value1 * value2;
break;
case "/":
if (value2 == 0)
throw new DivideByZeroException("You can't divide by zero!!!");
result = value1 / value2;
break;
}
txtResult.Text = result.ToString();
}
catch (FormatException ex1)
{
lblError.Text = ex1.Message;
}
catch (OverflowException ex2)
{
lblError.Text = ex2.Message;
}
catch (DivideByZeroException ex3)
{
lblError.Text = ex3.Message;
}
}
}
Note:
It is important to note that the more preferred method is the code-behind model rather than the inline
model. This method employs the proper segmentation between presentation and business logic in many
cases.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 25

Difference between Inline code and Code-behind.


Inline Code
Code Behind
The business logic is in <script> blocks in the same The HTML and controls are in the .aspx file, and the
.aspx file that contains the HTML and controls.
business logic is in a separate .aspx.cs or .aspx.vb
file.
When the page is deployed, the source code is All project class files (without the .aspx file) are
deployed along with the Web Forms page, since it compiled into a .dll file, which are deployed to the
is physically in the .aspx file. Though, we are not server without any source code. When a request for
able to see the code, only the results are rendered the page is received, then an instance of the project
when the page runs.
.dll file is created and executed.
The .aspx file derives from the Page class.
The code for the page is compiled into a separate
class from which the .aspx file derives.
When we write inline code we write code in the The
code-behind
approach
also
improved
same page with Html code between scripting tags. productivity (at some level) since the designer and
So Each time when there is a request for page it the developer can continue working simultaneously
compiles the code each time then server the page on the same set of application.
Like classic asp because inline code cannot create
dll.
It's also easier to build & test the UI and the
business logic (DLL) - separately or combined.
Code Behind separates user interface from actual programming. This means graphic designers would look
for only design matters while programmers work their way. Each specialized person work in their
irrespective area and doesn't disturb each other to perform optimized work.

Directives for ASP.NET Web Forms:


Directives specify settings that are used by the page and user-control compilers when the compilers process
ASP.NET Web Forms pages (.aspx files) and user control (.ascx) files.
ASP.NET directives can simply be described as instructions and settings used to describe how ASP.NET web form
pages (.aspx) or User control (.ascx) pages will be processed by the .NET Framework.

Directives are instructions, inserted at the top of an ASP.NET page, to control the behaviour of the asp.net
pages. So it is type of mixed settings related to how a page should render and processed.
Asp.Net web form page framework supports the following directives:
Directive

Description

@ Page

Defines page-specific attributes used by the ASP.NET page parser and compiler
and can be included only in .aspx files.

@ Master

Identifies a page as a master page and defines attributes used by the ASP.NET
page parser and compiler and can be included only in .master files.

@ Control

Defines control-specific attributes used by the ASP.NET page parser and compiler
and can be included only in .ascx files (user controls).

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 26

@ Register

Associates aliases with namespaces and classes, which allow user controls and
custom server controls to be rendered when included in a requested page or user
control.

@ Import

Imports a namespace into a page or user control explicitly.

@ PreviousPageType

Creates a strongly typed reference to the source page from the target of a crosspage posting.

@ Application

The Application directive is used to define application-specific attributes. It is


typically the first line in the Global.asax file.

@ Assembly

Links an assembly to the current page or user control declaratively.

@ Implements

Indicates that a page or user control implements a specified .NET Framework


interface declaratively.

@ Reference

Links a page, user control, or COM control to the current page or user control
declaratively.

@ OutputCache

Controls the output caching policies of a page or user control declaratively.

@ MasterType

Defines the class or virtual path used to type the Master property of a page.

@ WebService

Defines XML Web service specific (.asmx file) attributes used by the ASP.NET
parser and compiler.

We use these directives in our applications whether the page uses the code-behind model or the inline
coding model.
Basically, these directives are commands that the compiler uses when the page is compiled.
Directives are simple to incorporate into your pages.
A directive is written in the following format:
<%@ DirectiveName Attribute=Value %>
1. Page Directive:
Basically Page Directives are commands. These commands are used by the compiler when the page
is compiled.
When you want to specify the attributes for an ASP.NET page then you need to use @Page Directive.
As you know, an ASP.NET page is a very important part of ASP.NET, so this directive is commonly
used in ASP.NET.
Every ASP.NET Web Form generally begins with the @ Page directive. This defines page-specific
attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.
This directive can be used only in Web Forms pages. You can include only one @ Page directive per
.aspx file. Further, you can define only one Language attribute per @ Page directive, because only
one language can be used per page. Page Directives can be placed anywhere in .aspx file. But

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 27

standard practice is to include them at the top of the file. The Page directive is made of many
attributes. There are following major attributes:

Attributes:

Language:
It Specifies the language used when compiling all inline rendering (<% %> and <%= %>) and code
declaration blocks within the page. Values can represent any .NET Framework-supported language,
including C# or VB. Only one language can be used and specified per page.
AutoEventWireup:
Indicates whether the page's events are auto wired. True if event auto wiring is enabled; otherwise,
false.
By default its value is 'True' that means event of page class will be bound automatically with event
handlers but if it is 'false' then we need to bind event handler with page class event manually.
CodeFile:
It specifies the name of the compiled file that contains the class associated with the page. This
attribute is not used if the page uses inline code model as it represents to only code behind model.
Inherits:
Defines a code-behind class for the page to inherit. This can be any class derived from the Page
class. This attribute is used with the CodeFile attribute, which contains the path to the source file for
the code-behind class. The Inherits attribute is case-sensitive when using C# as the page language,
and case-insensitive when using Visual Basic as the page language.
Title:
It specifies a title for the page that is rendered within the HTML <title> tags in the response. The
title can also be accessed programmatically as a property of the page.
MasterPageFile:
Sets the path to the master page for the content page or nested master page. Supports relative and
absolute paths.
Theme:
Specifies a valid theme identifier to use on the page. When the Theme attribute is set without using
the StyleSheetTheme attribute, it overrides individual style settings on controls, enabling you to
create a unified and consistent look on a page.
StyleSheetTheme:
Specifies a valid theme identifier to use on the page. When the StyleSheetTheme attribute is set,
individual controls can override the stylistic settings contained in a theme. Thus a theme can provide
an overall look for a site, while the settings contained in the StyleSheetTheme attribute enable you
to customize particular settings on a page and its individual controls.
EnableTheming:
Indicates whether themes are used on the page. True if themes are used; otherwise, false. The
default is true.
EnableViewState:
Specifies whether view state is maintained across page requests. This value is true if view state is
maintained, or false if view state is not maintained. The default is true.
EnableSessionState:
Defines session-state requirements for the page. True if session state is enabled; ReadOnly if session
state can be read but not changed; otherwise, false. The default is true.
ErrorPage:
Defines a target URL for redirection if an unhandled page exception occurs.
ValidateRequest:
Indicates whether request validation should occur. If true, request validation checks all input data
against a hard-coded list of potentially dangerous values. If a match occurs,
an HttpRequestValidationException exception is thrown. The default is true.
This feature is enabled in the machine configuration file (Machine.config). You can disable it in your
application configuration file (Web.config) or on the page by setting this attribute to false.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 28

Syntax:
<%@ Page attribute="value" [attribute="value"...] %>
For Example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
2. Master Page Directive:
The @Master Directive is quite similar to the @Page Directive. The only difference is that the
@master directive is for Master pages. You need to note that, while using the @Master Directive you
define the template page's property. Then any content page can inherit all the properties defined in
the Master Page. But there are some properties that are only available in a Master Page.
It Defines master pagespecific (.master file) attributes that are used by the ASP.NET page parser
and compiler.
Syntax:
<%@ Master attribute="value" [attribute="value"...] %>
Example:
%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage1.master.cs"
Inherits="MasterPage" %
3. Control Directive:
Defines attributes that are specific to user controls (.ascx files) that are used by the ASP.NET page
parser and compiler.
The @ Control directive is used when we build an Asp.Net web user controls. The @Control directive
helps us to define the properties to be inherited by the user control. These values are assigned to
the user control as the page is parsed and compiled.
This directive can be used only in user controls. User controls are defined in files with the .ascx
extension. You can include only one @ Control directive per .ascx file. Further, you can define only
one Language attribute per @ Control directive, because only one language can be used per control.
Note:
The @ Control directive has a number of attributes in common with other directives that apply to an
entire source file, such as the @ Page directive (used in .aspx files for Web pages) and
the @ Master directive (used in .master files for master pages).
Syntax:
<%@ Control attribute="value" [attribute="value"...] %>
Example:
<%@ Control Language="C#" AutoEventWireup="false" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>

4. Register Directive:
The @ Register directive associates aliases with namespaces and class names for notation in custom
server control syntax. When you create a web user control and you drag and drop a web user control
onto your .aspx pages, the Visual Studio automatically creates a @ Register directive at the top of
the page. This register the user control on the page so that the control can be accessed on the .aspx
page by a specific name.
The @ Register directive can be included in Web Forms (.aspx files), Web User Controls (.ascx files),
and Master Pages (.master files).
Attributes:
Assembly
The assembly in which the namespace associated with the TagPrefix attribute resides.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 29

Note:
The assembly name cannot include a file extension. Also note that if the assembly attribute is
missing, the ASP.NET parser assumes that there is source code in the App_Code folder of the
application. If you have source code for a control that you want to register on a page without having
to compile it, place the source code in the App_Code folder. ASP.NET dynamically compiles source
files in the App_Code folder at run time.
Namespace:
The namespace of the custom control that is being registered.
Src:
The location (relative or absolute) of the declarative ASP.NET Web User Controls file to associate
with the TagPrefix and TagName pair.
TagName:
An arbitrary alias to associate with a class. This attribute is only used for user controls.
TagPrefix:
An arbitrary alias that provides a shorthand reference to the namespace of the markup being used
in the file that contains the directive.
Syntax:
<%@ Register attribute="value" [attribute="value"...] %>
Example:
<%@ Register Src="~/WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
5. Import Directive:
As you know you need to define namespaces in your .cs class file before using any type like class,
interface, struct, enum. So the @Import Directive imports namespaces. This directive supports just
a single attribute "Namespace" and this attribute takes a string value that specifies the namespace
to be imported. One thing you need to note is that the @Import Directive cannot contain more than
one attribute/value pair. But you can use multiple lines.
The @Import directive allows you to specify any namespaces to the imported to the Asp.Net pages
or user controls. By importing, all the classes and interfaces of the namespace are made available
to the page or user control.
Explicitly imports a namespace into an ASP.NET application file (such as a Web page, a user control,
a master page, or a Global.asax file), making all classes and interfaces of the imported namespace
available to the file. The imported namespace can be part of the .NET Framework class library or a
user-defined namespace.
The @ Import directive cannot have more than one namespace attribute. To import multiple
namespaces, use multiple @ Import directives.
A set of namespaces can be automatically imported into .aspx pages. The imported namespaces are
defined in the machine-level Web.config file, within the <namespaces> section of
the <pages> element. The following namespaces are automatically imported into all pages:
System
System.Collections
System.Collections.Specialized
System.Configuration
System.Text
System.Text.RegularExpressions
System.Web
System.Web.Caching
System.Web.Profile

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 30

System.Web.Security
System.Web.SessionState
System.Web.UI
System.Web.UI.HtmlControls
System.Web.UI.WebControls
System.Web.UI.WebControls.WebParts

Example:
<%@ Import Namespace="System.Data" %>
6. PreviousPageType Directive:
This directive specifies the page from which any cross-page posting originates.
The @PreviousPageType is a new directive makes excellence in asp.net 2.0 pages. The concept of
cross-page posting between Asp.Net pages is achieved by this directive. This directive is used to
specify the page from which the cross-page posting initiates.
Attributes:
TypeName: Specifies the type name for the previous page.
VirtualPath: Specifies the path to the file that generates the strong type.

Note:

Use
the
@
PreviousPageType
directive
to
get
strong
typing
against
the PreviousPage property. You can use the @ PreviousPageType directive only on a Web Forms
page (an .aspx file). If both attributes, TypeName and VirtualPath, are defined,
the @ PreviousPageType directive will fail.

Example:
<%@ PreviousPageType VirtualPath="~/YourPreviousPageName.aspx" %>
7. Application Directive:
The Application directive defines application-specific attributes. It is provided at the top of the
global.asax file.
Application directives specify optional application-specific settings used by the ASP.NET parser when
processing ASP.NET global application (.asax) files. Application directives are located at the top of
the Global.asax file.
Note that the @ Application directive can be used only in Global.asax files, while the other directives
are used in other ASP.NET files such as Web pages (.aspx files) and user controls (.ascx files).
Application Directive supports following attributes: Language, Inherits, and CodeBehind.
Example:
<%@ Application Language="C#" %>
8. Assembly Directive:
The @ Assembly directive links an assembly to the page or the application at parse time. This could
appear either in the global.asax file for application-wide linking, in the page file, a user control file
for linking to a page or user control.
OR
Links an assembly to an ASP.NET application file (such as a Web page, a user control, a master page,
or a Global.asax file) during compilation, making all the assembly's classes and interfaces available
for use.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 31

This directive supports the two attributes Name and Src. The Name attribute defines the assembly
name (The assembly name does not include a file name extension) and the Src attribute defines the
path to a source file to dynamically compile and link against.

Note:
You must include either a Name or a Src attribute in a @ Assembly directive, but you cannot
include both within the same directive. If you need to use both of these attributes, you must include
multiple @ Assembly directives in the file.
Example:
<%@Assembly Name="MyAssembly" %>
<%@Assembly Src="MyAssembly.cs" %>
9. Implements Directive:
The @ Implements Directive gets the ASP.NET pages to implement .Net framework interfaces. This
directive only supports a single attribute i.e. Interface.
OR

The Implement directive indicates that the web page, master page or user control page must
implement the specified .Net framework interface.
Example:
<%@ Implements Interface="System.Web.UI.IValidator" %>
10.Reference Directive:

The Reference directive indicates that another page or user control should be dynamically
compiled and linked against the current ASP.NET file (Web page, user control, or master page) in
which this directive is declared.
Attributes:
Page:
The external page that ASP.NET should dynamically compile and link to the current file that
contains the @ Reference directive.
Control:
The external user control that ASP.NET should dynamically compile and link to the current
file that contains the @ Reference directive.
VirtualPath:
The virtual path for the reference. Can be any file type as long as a build provider exists. For
example, it would be possible to point to a master page.
Example:
<%@Reference VirtualPath="~/MyControl.ascx" %>
11.OutputCache Directive:
The OutputCache directive controls the output caching policies of a web page or a user control.
Attributes: The very important attributes for the @OutputCache directive are as follows:
Duration:
The time, in seconds, that the page or user control is cached. Setting this attribute on a page
or user control establishes an expiration policy for HTTP responses from the object and will
automatically cache the page or user control output.
VaryByParam:
A semicolon-separated list of strings used to vary the output cache. By default, these strings
correspond to a query string value sent with GET method attributes, or a parameter sent
using the POST method. When this attribute is set to multiple parameters, the output cache

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 32

contains a different version of the requested document for each combination of specified
parameters. Possible values include none, an asterisk (*), and any valid query string
or POST parameter name.
Example:
<%@ OutputCache Duration ="180" VaryByParam="None" %>
12.MasterType Directive:
The @MasterType Directive connects a class name to the ASP.NET page for getting strongly typed
references or members contained in the specified Master Page.
This directive supports the two attributes TypeName and VirtualPath.
TypeName sets the name of the derived class from which to get the strongly typed or reference
members and VirtualPath sets the location of the page from which these are retrieved.
If both attributes, TypeName and VirtualPath, are defined, the @ MasterType directive will fail.
Example:
<%@ MasterType VirtualPath="~/MasterPage1.master" %>
13.WebService Directive:
Defines XML Web service specific (.asmx file) attributes used by the ASP.NET parser and compiler.
Attributes:
Class
The WebService directive's Class attribute specifies the name of the class implementing the
web service. The Class attribute is required. The class specified can reside either in a separate
code-behind file, or in-line in the .asmx file.
CodeBehind
Specifies the source file implementing the XML Web service, when the class implementing the
XML Web service does not reside in the same file.
Debug
Indicates whether the XML Web service should be compiled with debug symbols. True if the
XML Web service should be compiled with debug symbols; otherwise, false.
Language
Specifies the language used when compiling all inline code within the XML Web service file
(.asmx). The values can represent any .NET-supported language, including C#, and VB,
which refer to Visual C#, and Visual Basic .NET respectively.
Example:

<%@
WebService
Language="C#"
Class="WebService %>

CodeBehind="~/App_Code/WebService.cs"

ASP.NET Application Folders:


ASP.NET uses a file-based approach. That means, all class files, resource files, data files and folders are
maintained in a hierarchical structure.
Advantages of ASP.NET Application Folders:
Following are the main advantages of use of ASP.NET's Application Folders:

We can maintain resources (classes, images, code, databases, and themes etc...) in an organized
manner, which allows us to develop and maintain sites easily.
All files and folders are accessible through the entire application.
We can add as many files as required.
Files are compiled dynamically when required.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 33

Types of Application Folders: ASP.NET recognizes certain folder names that you can use for
specific types of content.
These are the following types of Application Folders:
1. App_Code
2. App_Data
3. App_Themes
4. Bin
5. App_WebReferences
6. App_Browsers
7. App_LocalResources
8. App_GlobalResources
The content of application folders, except for the App_Themes folder, is not served in response to Web
requests, but it can be accessed from application code.
These all above folders can be created as per need in our web site to contain their corresponding items as
following:
Open Solution Explorer, Right Click Application Root -> Select Add -> Add ASP.NET Folder -> Click
Any Of The ASP.NET Folder Which Required to Add It in your Web Site.

The App_Code Folder:


As its name suggests, the App_Code Folder stores classes, typed data sets, etc. All the items that are stored
in App_Code are automatically accessible throughout the application. If we store any class files
(like .cs or .vb) it compiles them automatically. It automatically creates type data sets from .xsd (XML
schema) files, and creates XML web service proxy classes from WSDL.
It contains source code for shared classes and business objects (for example, .cs, and .vb files) that you
want to compile as part of your application. In a dynamically compiled Web site project, ASP.NET compiles
the code in the App_Code folder on the initial request to your application. Items in this folder are then
recompiled when any changes are detected.
Code in the App_Code folder is referenced automatically in your application. The App_Code folder can
contain subdirectories of files, which can include class files that in different programming languages.
We can add an App_Code folder, by Solution Explorer Right Click Add ASP.NET
Folder App_Code. The App_Code folder is now added to your application.
Note: Try to add one more App_Code folder by using the same steps. Oops... the App_Code folder is no
longer available there. So, ASP.NET allows you to add an App_Code folder only once.
The App_Code folder can contain as many files and subfolders as you need. You can organize your source
code in any way that you find convenient, and ASP.NET will still compile all of the code into a single assembly
that is accessible to other code anywhere in the Web application.
Inferring the Programming Language of the App_Code Folder
The App_Code folder is not explicitly marked as containing files written in any one programming
language. Instead, the ASP.NET infers which compiler to invoke for the App_Code folder based on the files
it contains. If the App_Code folder contains .vb files, ASP.NET uses the Visual Basic compiler; if it contains
.cs files, ASP.NET uses the C# compiler, and so on.
Multiple Programming Languages in the App_Code Folder
Because the source code in the App_Code folder is compiled into a single assembly, all the files in the
App_Code folder must be in the same programming language. For example, the App_Code folder cannot
include source code in both Visual Basic and C#.
If we want to store different classes like .cs or .vb, then what will happen? If we kept both .cs and .vb classes
in the same folder, it will give following compilation error:

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 34

This is because all the classes contained in the App_Code folder are built into a single assembly and it can't
have different languages at root level, or even at child level folders in following manner:

We have a solution to overcome this problem. We have to create separate folders for C# and for VB or
other classes.
Store class files separately in those folders and configure the folder hierarchy in the web.config file.

However, we can configure our Web application to treat subfolders of the App_Code folder as separate
compliable units. Each folder can then contain source code in a different programming language. The
configuration is specified by creating a codeSubDirectories element in the compilation element of the
Web.config file and adding a reference to the subfolder. The following example illustrates how we would
configure subfolders named CSharp and VisualBasic to compile into separate assemblies:
<!Configuration for Compilation of Different Languages -->
<compilation debug="false">
<codeSubDirectories>
<add directoryName="CSharp" />
<add directoryName="VisualBasic" />
</codeSubDirectories>
</compilation>

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 35

The references to the CSharp and VisualBasic subfolders do not need to include any information about what
programming language is contained in the subfolder. As with the App_Code folder itself, ASP.NET infers the
compiler to use based on the files in the subfolder.

The App_Data Folder:


The App_Data folder is used as a data storage for the web application. It can store files such as .mdf, .mdb,
.accdb, and XML. It manages all of your application's data centrally. It is accessible from anywhere in your
web application.
OR
You can say, it contains application data files including .mdf database files, XML files, text files as well as
other data store files. The App_Data folder is used by ASP.NET to store an application's local database, such
as the database for maintaining membership and role information.

Note: As a security measure, files in the App_Data folder are not served by the Web server. Do not store
any Web pages in the App_Data folder because users will see an error if they request a page from that
folder. The real advantage of the App_Data folder is that, any file you place there won't be downloadable.

The App_Themes Folder:


Themes are used to define visual styles for web pages. Themes are made up of a set of elements: Skins,
Cascading Style Sheets (CSS), images, and other resources. Themes can be applied at the application,
page, or server control level.
If you want to give your web sites a consistent look, then you need to design themes for your web
application. The App_Themes folder contains all such themes. When we add an App_Themes folder, a
subfolder with name Theme1 will be automatically created. We can change the name of the theme folder
as per our requirements. Even App_Themes folder can contain any numbers of theme subfolders that
represents different themes and each theme folder can contains a collection of files (.skin and .css files, as
well as image files and generic resources) that define the appearance of ASP.NET Web pages and controls.
A skin file has the file name extension .skin and contains property settings for individual server side controls
such as Button, Label, TextBox, or Calendar controls. Control skin settings are like the control markup itself,
but contain only the properties you want to set as part of the theme.
You create .skin files in the Theme folder. A .skin file can contain one or more control skins for one or more
control types. You can define skins in a separate file for each control or define all the skins for a theme in a
single file.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 36

A theme can also include a cascading style sheet (.css file) that represents to html generic properties. When
you put a .css file in the theme folder, the style sheet is applied automatically as part of the theme. You
define a style sheet using the file name extension .css in the theme folder.

The Bin Folder:


Contains compiled assemblies (.dll files) for controls, components, or other code that you want to reference
in your application. Any classes represented by code in the Bin folder are automatically referenced in your
application.

The Bin folder is used for keeping assemblies inside it. We can access those as a reference from
anywhere of our web application. Use of Bin folder comes into the picture if we use any class library
within our web application.
Suppose we are creating a class library called TestLib. After building the library, we will get TestLib.dll.
Now, right click on Application Root in Solution Explorer of a Website Add References Browse,
locate

the

TestLib.dll

library

assembly,

and

click

on

OK.

Check

the

Bin

folder,

it

will

contain TestLib.dll and TestLib.pdb files.

Assemblies in the Bin folder do not need to register on the system, ASP.NET recognizes the presence
of DLLs inside the Bin Folder. Keeping .pdb files inside Bin folder helps us in debugging. The main
limitation of storing assemblies in the Bin folder is that their scope is limited to the current application.
Therefore, they cannot access any code outside of current web application.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 37

The App_WebReferences Folder:


As the name suggests, the App_WebReferences folder contain references to any web services. If we
added

any

web

services

with

our

web

application,

they

go

automatically

into

the App_WebReferences folder, in the same way as if we added any DLLs, they would go under
the Bin folder.

The App_Browsers Folder:


It contains browser definitions (.browser files) that ASP.NET uses to identify individual browsers and
determine their capabilities.
OR

The App_Browsers folder contains browser information files (.browser files). These files are XML based
files which are used to identify the browser and browser capabilities.
You can find a list of globally accessible browser files in the CONFIG\Browsers folder under the installation
path. In addition, if you want to change any part of these default browser definition files, just copy the
appropriate browser file from the Browsers folder to your applications \App_Browsers folder and change
the definition. You will find the browser files in the following location:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Browsers
If you want to change a .browser file, just copy the file to the App_Browsers folder and change it. You
can create new browser files by just clicking on Add New Item of the App_Browsers folder

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 38

The App_LocalResources Folder:


It contains resources (.resx and .resources files) that are associated with a specific page, user control, or
master page in an application.

Local resources are specific to a single web page, and should be used for providing multilingual
functionality on a web page.
Local resources must be stored in the App_LocalResources subfolder of the folder containing the web
page. Because you might have local resources for every page in your web application, you might have
App_LocalResources subfolders in every folder.
Resource file names should be like <pageName>[.langauge].resx. Some examples of local resource
files are, Mypage.aspx.ex.resx and Mypage.aspx.de.resx. Default.aspx.resx is the base resource file to
use if no other resource file matches with the user's current culture.
If you want to create local resources for a page, open the design view of the page and then from Tool
Menu select Generate Local Resource. You will then see that a resource file is automatically created
in the corresponding App_LocalResources folder.

Note:

Default.aspx.resx

is

the

resource

file

for

Default.aspx.

Resource

files

are

inside

the App_LocalResource folder.

The App_GlobalResources Folder:


It contains resources (.resx and .resources files) that are compiled into assemblies with global scope.
Resources in the App_GlobalResources folder are strongly typed and can be accessed programmatically.

The App_GlobalResources folder can be read from any page or code that is anywhere in the web site.
Global resources must be stored in the App_GlobalResources folder at the root of the application. We
should use theApp_GlobalResources folder when we need a single resource for multiple web pages.
We can define ASP.NET control properties by manually associating them with resources in global
resource files. You can add a global resource file by right clicking on the App_GlobalResources folder
and clicking on Add -> Add New Items. Add .resx files as resources.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 39

Note: The main purpose of resource files is localization & globalization of the web application.

ASP.Net Page Life Cycle:


When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing
steps. These include initialization, instantiating controls, restoring and maintaining state, running event
handler code, and rendering. It is important for you to understand the page life cycle so that you can write
code at the appropriate life-cycle stage for the effect you intend. Additionally, if you develop custom
controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control
properties with view-state data, and run any control behaviour code. (The life cycle of a control is based on
the page life cycle, but the page raises more events for a control than are available for an ASP.NET page
alone.)

General Page Life-cycle Stages:

In general terms, the page goes through the stages outlined in the following table.
Stage

Description

Page
request

The page request occurs before the page life cycle begins. When the page is requested by
a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore
beginning the life of a page), or whether a cached version of the page can be sent in
response without running the page.

Start

In the start step, page properties such as Request and Response are set. At this stage, the
page also determines whether the request is a postback or a new request and sets
the IsPostBack property.

Page
initialization

During page initialization, controls on the page are available and each
control's UniqueID property is set. Any themes are also applied to the page. If the current

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 40

request is a postback, the postback data has not yet been loaded and control property
values have not been restored to the values from view state.
Load

During load, if the current request is a postback, control properties are loaded with
information recovered from view state and control state.

Validation

During validation, the Validate method of all validator controls is called, which sets
the IsValid property of individual validator controls and of the page.

Postback
event
handling

If the request is a postback, any event handlers are called.

Rendering

Before rendering, view state is saved for the page and all controls. During the rendering
phase, the page calls the Render method for each control, providing a text writer that
writes its output to the OutputStream of the page's Response property.

Unload

Unload is called after the page has been fully rendered, sent to the client, and is ready to
be discarded. At this point, page properties such as Response and Request are unloaded
and any clean-up is performed.

Life-Cycle Events
Within each stage of the life cycle of a page, the page raises events that you can handle to run your own
code. For control events, you bind the event handler to the event, either declaratively using attributes such
as OnClick, or in code.
Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names
and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute
of the @ Page directive is set to true (or if it is not defined, since by default it is true), page events are
automatically bound to methods that use the naming convention of Page_Event, such
as Page_Load and Page_Init.
The following table lists the page life-cycle events that you will use most frequently. There are more events
than those listed; however, they are not used for most page processing scenarios. Instead, they are
primarily used by server controls on the ASP.NET Web page to initialize and render themselves.
Following are the page life cycle events:

PreInit
PreInit is the first event in page life cycle.
We use this event for the following:
Check the IsPostBack property to determine whether this is the first time the page is
being processed.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 41

This event can be handled by overriding the OnPreInit method or creating a Page_PreInit handler as
following:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
}
OR
protected void Page_PreInit(object sender, EventArgs e)
{
}

Init
Raised after all controls have been initialized and any skin settings have been applied. Use this event
to read or initialize control properties.
This event can be handled by overriding the OnInit method or creating a Page_Init handler as
following:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
OR
protected void Page_Init(object sender, EventArgs e)
{
}

InitComplete
Raised by the Page object. Use this event for processing tasks that require all initialization be
complete.
This event can be handled by overriding the OnInitComplete method or creating a Page_InitComplete
handler as following:
protected override void OnInitComplete(EventArgs e)
{
base.OnInitComplete(e);
}
OR
protected void Page_InitComplete (object sender, EventArgs e)
{
}

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 42

PreLoad
Use this event if you need to perform processing on your page or control before the Load event.
After the Page raises this event, it loads view state for itself and all controls, and then processes
any postback data included with the Request instance.
This event can be handled by overriding the OnPreLoad method or creating a Page_PreLoad handler
as following:
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad (e);
}
OR
protected void Page_PreLoad (object sender, EventArgs e)
{
}

Load
The Page calls the OnLoad event method on the Page, then recursively does the same for each
child control, which does the same for each of its child controls until the page and all controls are
loaded.
Use the OnLoad event method to set properties in controls and establish database connections.
This event can be handled by overriding the OnLoad method or creating a Page_Load handler as
following:
protected override void OnLoad(EventArgs e)
{
base.OnLoad (e);
}
OR
protected void Page_Load (object sender, EventArgs e)
{
}

LoadComplete
Use this event for tasks that require that all other controls on the page be loaded.
The loading process is completed, control event handlers are run, and page validation takes place.
This

event

can

be

handled

by

overriding

the

OnLoadComplete

method

or

creating

Page_LoadComplete handler as following:


protected override void OnLoadComplete (EventArgs e)
{
base.OnLoadComplete (e);
}

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 43

OR
protected void Page_LoadComplete (object sender, EventArgs e)
{
}

PostBack Events (Control Events)


Use these events to handle specific control events, such as a Button control's Click event or
a TextBox control's TextChanged event.
Note:
In a postback request, if the page contains validator controls, check the IsValid property of
the Page and of individual validation controls before performing any processing.
For Example: Button Controls Click Event
protected void Button1_Click(object sender, EventArgs e)
{
}

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.
OR
Use this event to perform any updates before the server control is rendered to the page. Any
changes in the view state of the server control can be saved during this event. Such changes made
in the rendering phase will not be saved.
The PreRender event occurs for each control on the page. Use the event to make final changes to
the contents of the page or its controls.
This event can be handled by overriding the OnPreRender method or creating a Page_ PreRender
handler as following:
protected override void OnPreRender (EventArgs e)
{
base.OnPreRender (e);
}
OR
protected void Page_PreRender (object sender, EventArgs e)
{
}

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 44

PreRenderComplete
As the PreRender event is recursively fired for all child controls, this event ensures the completion
of the pre-rendering phase.
OR
The PreRenderComplete event is raised when the pre-render stage of the page life cycle is complete.
At this stage of the page life cycle, the page is ready to render to the output.
This is the last event raised before the page's view state is saved.
This event can be handled by overriding the OnPreRenderComplete method or creating a Page_
PreRenderComplete handler as following:
protected override void OnPreRenderComplete (EventArgs e)
{
base.OnPreRenderComplete (e);
}
OR
protected void Page_PreRenderComplete (object sender, EventArgs e)
{
}

SaveStateComplete
Before this event occurs, ViewState has been saved for the page and for all controls. Any changes
to the page or controls at this point will be ignored.
Use this event perform tasks that require view state to be saved, but that do not make any changes
to controls.
This event can be handled by overriding the OnSaveStateComplete method or creating a Page_
SaveStateComplete handler as following:
protected override void OnSaveStateComplete (EventArgs e)
{
base.OnSaveStateComplete (e);
}
OR
protected void Page_SaveStateComplete (object sender, EventArgs e)
{
}

Render
Render is not an event but this is the phase where the HTML of your page will get rendered to the
output stream with the help of HTMLTextWriter. You can override the Render method of page if you
want to write your own code rather than the actual HTML text. As like below:

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 45

protected override void Render(HtmlTextWriter writer)


{
base.Render(writer);
Response.Write("<h1>Hello ASP.NET</h1>");
}

UnLoad
This is the last event that gets fired. This is the page cleaning process like closing the open file
connections etc., so in this process you cannot do any kind of manipulation with data that affect the
rendering, you are restricted to use Response object also, and doing such you will get an exception
message.
Clean-up can be performed on following:(a) Instances of classes i.e. objects
(b) Closing opened files
(c) Closing database connections.
This event can be handled by overriding the OnUnload method or creating a Page_ Unoad handler
as following:
protected override void OnUnload (EventArgs e)
{
base.OnUnload (e);
}
OR
protected void Page_Unload (object sender, EventArgs e)
{
}

Working with PostBacks:


All the web applications are running on Web Servers. Whenever a user made a request to the web server,
the web server has to return the response to the user. PostBack is the name given to the process of
submitting all the information that the user is currently working on and send it all back to the server.
Postback is actually sending all the information from client to web server, then web server process all those
contents and returns back to client.
A postback originates from the client side browser. When the web page and its contents are sent to the web
server for processing some information and then, the web server posts the same page back to the client
browser. Normally one of the controls event (e.g. button click) on the page can initiate a postback. Then
the state of this control and all other controls on the page is Posted Back to the web server.
PostBack is the name given to the process of submitting an ASP.NET page to the server for processing.
A postback is just that a posting back to the same page. The postback contains all the form information
collected on the initial page for processing if required.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 46

In Classic ASP, developers had their pages post to other pages within the application. ASP.NET pages
typically post back to themselves to process events (such as a button controls click event).
For this reason, we must differentiate between posts for the first time a page is loaded by the end user and
postbacks.
The Page class includes a property called the IsPostBack property, which we can use to detect whether a
request is the first instance for a particular page or is a postback from the same page.
IsPostBack Property gets a Boolean value that indicates whether the page is being rendered for the first
time or is being loaded in response to a postback. true if the page is being loaded in response to a client
postback; otherwise, false.
IsPostBack is normally used on Page_Load event to detect if the web page is getting generated due to
postback requested by a control on the page or if the page is getting loaded for the first time.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Do Processing When a Page is Loaded First Time without PostBack
}
else
{
// Process Submitted Data with PostBack
}
}

Cross-Page Posting:
Cross Page PostBack in ASP.NET:
Cross-page posting is desired in a scenario where data is collected on one Web page and processed on
another Web page. ASP.NET 2.0 introduces a new property in the Page class called PreviousPage which
gets the page that posted to the current page.
Normally we use the term postback when an ASP.NET page submits its content back to that page itself. But
there can be situation when a page needs to submit its content to a different target page. This is known as
cross page postback.
ASP.NET by default, submits the form to the same page. Cross page posting is submitting the form to a
different page. This is usually required when you are creating a multi-page form to collect information from
the user on each page. When moving from the source to the target page, the values of controls in the
source page can be accessed in the target page.
"To use cross-page posting, you have to use the "PostBackUrl" attribute to specify the page we want to
post".
Cross Page posting is used to submit a form on one page (say Default.aspx) and retrieve values of
controls of this page on another page (say Default2.aspx).
To determine whether the page was invoked from a cross-page posting the Page class exposes a property
named IsCrossPagePostBack returns either true or false.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 47

Getting Information from the Source Page:


When you configure a page for cross-page posting, you frequently want to get information from the source
page. This might include the information from controls on the pagethat is, the information being posted
by the browseras well as public properties of the source page.

Getting Control Values


The Page class exposes a property named PreviousPage. If the source page and target page are in the same
ASP.NET application, the PreviousPage property in the target page contains a reference to the source page.
(If the page is not the target of a cross-page posting, or if the pages are in different applications,
the PreviousPage property is not initialized.) By default, the PreviousPage property is typed as Page.
Using the reference in the PreviousPage property, you can search for controls on the source page and
extract their value. You typically do this with the FindControl method.
Note: If you are coding the source page specifically to be able to share information with target pages, an
easier way to make control values available to the target page is to expose them as public properties.
The following code example shows how you can get the value of the TextBox1 control on the source page.

if (Page.PreviousPage != null && PreviousPage.IsCrossPagePostBack)


{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}
Note that if the current page is not the target of a cross-page post, the PreviousPage property
returns null (Nothing in Visual Basic).

Getting Public Property Values from the Source Page


In the target page of a cross-page posting, you can also get the values of public members of the source
page. The most common scenario is that the source page defines public properties and you want to get
their values on the target page.
To get public members of the source page, you must first get a strongly typed reference to the source
page.
You can do so in a number of ways. The first is to include a @ PreviousPageType directive in the target
page, which allows you to specify the source page, as in this example:
<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>
When this directive is included, the PreviousPage property is strongly typed to the class of the referenced
source page. As a consequence, you can directly reference public members of the source page. You can
specify the type of the source page either directly, using a type attribute, or indirectly by explicitly
referencing the source page in a VirtualPath attribute, as shown in the above example.
The following code example shows a portion of a source page containing a public property
named FirstName that exposes the value of a TextBox control named txtFirstName.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 48

public String FirstName


{
get
{
return txtFirstName.Text.Trim();
}
}
Note:
Properties on the source page that are created primarily to expose values for cross-page posting are usually
read-only properties. Although the source page can contain public read/write properties, setting a source
page property from the target page property generally has no purpose, because the value will not be
persisted.
If the target page contains a PreviousPageType directive that points to the source page, you can access
the source page's FirstName property using code such as the following.
Label1.Text = PreviousPage.FirstName;
Examples:
There are two ways we can use cross page postbacks in ASP.NET
1st Method
In this Ive created a Default.aspx page with two textbox and one button , button click will post back to
Default2.aspx and there we will retrieve and show values of both textboxes

Default.aspx:
Source View:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div align="center" style="border:5px solid green">
<h1>Cross Page PostBack Example</h1>
<b>First Name:</b>
<asp:TextBox ID="txtFirstName" runat="server">
</asp:TextBox>
<br />
<br />
<b>Last Name:</b>
<asp:TextBox ID="txtLastName" runat="server">
</asp:TextBox><br />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server"
PostBackUrl="~/Default2.aspx"
Text="Submit to Second Page" />
<br /><br />
</div>
</form>
</body>
</html>
Note: Don't forget to set PostBackUrl Property of Button PostBackUrl="~/Default2.aspx"

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 49

Design View:

Now to retrieve values of textboxes on Default2.aspx page, write below mentioned code in
Page_Load event of second page (Default2.aspx)
Code File (Default2.aspx.cs):
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
//Check whether previous page is cross page post back or not
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
TextBox txtFirstName = (TextBox)PreviousPage.FindControl("txtFirstName");
TextBox txtLastName = (TextBox)PreviousPage.FindControl("txtLastName");
Response.Write("Your First Name: " + txtFirstName.Text.Trim());
Response.Write("<br />");
Response.Write("Your Last Name: " + txtLastName.Text.Trim());
}
else
{
Response.Redirect("Default.aspx");
}
}
}
2nd Method
Using Property to expose and consume values of TextBox:
If we are using this method then we don't need to use FindControl method at all
For this we need to create property in code behind of the page to be cross page post back (Default.aspx)

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 50

Html of the page (Default.aspx) needs no changes,


C# code behind for Default.aspx:

Code File (Default.aspx.cs):


using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
}
public TextBox pbTxtFirstName
{
get
{
return txtFirstName;
}
}

public TextBox pbTxtLastName


{
get
{
return txtLastName;
}
}

Now to retrieve or consume exposed properties on Second page we need to add below mentioned page
directive in html source of Default2.aspx page (usually at the top of page)
<%@ PreviousPageType VirtualPath="~/Default.aspx" %>
Now write this code in Page_Load event of second page to retrieve values of controls
C# Code

Code File (Default2.aspx.cs):


using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.

P a g e | 51

using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Check whether previous page is cross page post back or not
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
Response.Write("Your First Name: " + PreviousPage.pbTxtFirstName.Text.Trim());
Response.Write("<br />");
Response.Write("Your Last Name: " + PreviousPage.pbTxtLastName.Text.Trim());
}
else
{
Response.Redirect("Default.aspx");
}
}
}

Output:

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 52

Working with ASP.Net Web Forms Controls:


Controls are main building blocks of the graphical user interface, which include text boxes, buttons, check
boxes, list boxes, labels, and numerous other controls. Using these controls, the users can enter data, make
selections and indicate their preferences.
Controls are also used for structural jobs, like validation, data access, security, creating master pages, and
data manipulation.
ASP.NET uses five types of web controls, which are following:

HTML Controls

HTML Server Controls

ASP.NET Server Controls

ASP.NET Ajax Server Controls

User Controls and Custom Controls

HTML Controls:
By default, HTML elements on an ASP.NET Web page are not available to the server; they are
treated as opaque text that is passed through to the browser. However, by converting HTML
elements to HTML server controls, you expose them as elements you can program in server-based
code.
OR
HtmlControls are just programmable HTML tags. By default these tags are literal text and you
can't reference them with server side code. To "see" any HTML tag with your ASP.NET server side
code you need to add runat="server" and some value to ID parameter. For example, to work with
<textarea> HTML tag with server side code, you can use HTML code like this:
<textarea runat="server" id="TextArea1" cols="20" rows="2"></textarea>
By default most commonly used HTML controls (elements) can be viewed in the toolbox of design
view of the page in Visual Studio IDE.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 53

These are following major HTML Controls:

Input (Button):
<input type="button" id="button1" value="Button" />
Output:

Input (Reset):
<input type="reset" id="button1" value="Reset" />
Output:

Input (Submit):
<input type="submit" id="button1" value="Submit" />
Output:
Input (Text):
<input type="text" id="textbox1" />
Output:

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 54

Input (File):
<input type="file" id="fileupload1" />
Output:

Input (Password):
<input type="password" id="password1" />
Output:

Input (CheckBox):
<input type="checkbox" id="checkbox1" />
<label for="checkbox1">Select</label>
Output:

Input (Radio):
<input type="radio" id="rdb1" name="Gender" />
<label for="rdb1">Male</label>
<input type="radio" id="rdb2" name="Gender" />
<label for="rdb2">Female</label>
Output:

Input (Hidden):
<input type="hidden" id="hidden" value="ASP.NET" />
Output:
Invisible on the page.
Textarea:
<textarea id="textarea1" rows="5" cols="50" ></textarea>
Output:

Table
<table id="table1" style="width:100%;" border="1">
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
Output:

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 55

Image
<img id="img1" src="Images/Img1.jpg" alt="Image Element" title="This is an image" width="300"
height="300" />
Output:

Select: (DropDownList)
<select id="ddl1">
<option>Select</option>
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
</select>
Output:

OR (ListBox)
<select id="ddl1" multiple="multiple">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
</select>
Output:

Horizontal Rule
<hr />
Output:
Div
<div></div>
Output:
Its Container

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 56

HTML Server Controls:


The HTML server controls are Hypertext Markup Language (HTML) elements that include
a runat=server attribute. The HTML server controls have the same HTML output and the same properties
as their corresponding HTML tags.
OR
The HTML server controls are basically the standard HTML controls enhanced to enable server side
processing. The HTML controls such as the header tags, anchor tags, and input elements are not processed
by the server but are sent to the browser for display.
They are specifically converted to a server control by adding the attribute runat="server" and adding an id
attribute to make them available for server-side processing.
For example, consider the HTML input control:
<input type="text" />
It could be converted to a server control, by adding the runat and id attribute:
<input type="text" id="text1" runat="server" />

In addition, HTML server controls provide automatic state management and server-side events. HTML server controls
offer the following advantages:

The HTML server controls map one to one with their corresponding HTML tags.

When the ASP.NET application is compiled, the HTML server controls with the runat=server attribute are compiled
into the assembly.

Most controls include an OnServerEvent for the most commonly used event for the control. For example, the
<input type=button> control has an OnServerClick event.

When the ASP.NET page is reposted, the HTML server controls keep their values.

Note: All HTML server controls must be within a <form> tag with 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. All HTML elements mapped to a corresponding
classes in ASP.NET that represents as server control to use programmatically. HTML control classes found
in the System.Web.UI.HtmlControls namespace. HtmlControl is a base class for all HTML server controls
containing all of the common properties.
The System.Web.UI.HtmlControls namespace contains classes that allow you to create HTML server
controls on a Web Forms page. HTML server controls run on the server and map directly to standard HTML
tags supported by most browsers. This allows you to programmatically control the HTML elements on a Web
Forms page.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 57

These are following HTML server controls classes that are available in ASP.NET:
Class

Description

HtmlAnchor

Allows programmatic access to the HTML <a> element on the server.

HtmlArea

Provides programmatic access to the HTML <area> element on the server.

HtmlAudio

Provides programmatic access to the HTML <audio> element on the server.

HtmlButton

Allows programmatic access to the HTML <button> tag on the server.

HtmlContainerControl

Serves as the abstract base class for HTML server controls that map to HTML elements that
are required to have an opening and a closing tag.

HtmlControl

Defines the methods, properties, and events common to all HTML server controls in the
ASP.NET page framework.

HtmlElement

Provides programmatic access to the document's <html> element on the server, which
represents the document's root.

HtmlEmbed

Provides programmatic access to the HTML embed element on the server.

HtmlForm

Provides programmatic access to the HTML <form> element on the server.

HtmlGenericControl

Defines the methods, properties, and events for all HTML server control elements not
represented by a specific .NET Framework class.

HtmlHead

Provides programmatic access to the HTML head element in server code.

HtmlIframe

Provides programmatic access to the HTML <iframe> element on the server.

HtmlImage

Provides programmatic access for the HTML <img> element on the server.

HtmlInputButton

Allows programmatic access to the HTML <input type= button>, <input type= submit>,
and <input type= reset> elements on the server.

HtmlInputCheckBox

Allows programmatic access to the HTML <input type= checkbox> element on the server.

HtmlInputControl

Serves as the abstract base class that defines the methods, properties, and events common
to all HTML input controls, such as the <input type=text>, <input type=submit>, and <input
type= file> elements.

HtmlInputFile

Allows programmatic access to the HTML <input type= file> element on the server.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 58

HtmlInputGenericControl

Defines the methods, properties, and events for server-side access to the HTML5 input
element.

HtmlInputHidden

Allows programmatic access to the HTML <input type=hidden> element on the server.

HtmlInputImage

Allows programmatic access to the HTML <input type= image> element on the server.

HtmlInputPassword

Allows programmatic access to the HTML <input type= password> element on the server.

HtmlInputRadioButton

Allows programmatic access to the HTML <input type= radio> element on the server.

HtmlInputReset

Allows programmatic access to the HTML <input type=reset> element on the server.

HtmlInputSubmit

Allows programmatic access to the HTML <input type= submit> element on the server.

HtmlInputText

Allows programmatic access to the HTML <input type= text> and <input type=
password> elements on the server.

HtmlLink

Allows programmatic access to the HTML link element on the server.

HtmlMeta

Allows programmatic access to the HTML <meta> tag on the server.

HtmlSelect

Allows programmatic access to the HTML <select> element on the server.

HtmlTable

Allows programmatic access on the server to the HTML <table> element.

HtmlTableCell

Represents the <td> and <th> HTML elements in an HtmlTableRow object.

HtmlTableCellCollection

A collection of HtmlTableCell objects that represent the cells in a single row of an


HtmlTable control. This class cannot be inherited.

HtmlTableRow

Represents the <tr> HTML element in an HtmlTable control.

HtmlTableRowCollection

A collection of HtmlTableRow objects that represent the rows of an HtmlTable control. This
class cannot be inherited.

HtmlTextArea

Allows programmatic access to the <textarea> HTML element on the server.

HtmlTitle

Allows programmatic access to the HTML <title> element on the server.

HtmlVideo

Provides programmatic access to the HTML <video> element on the server.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 59

Creating HTML Server Controls Programmatically:


In order to create HTML Server Controls programmatically, you need to use the following steps:
Steps:
Step1: Import the corresponding namespace in which all the html control classes found i.e.
System.Web.UI.HtmlControls
Step2: Declare the control class object
Step3: Instantiate the control class object
Step4: Set the possible properties values which are required
Step5: Add the event handlers & their event definition if required
Step6: Add the control object to a form container
For Example: Creating an HTML Input TextBox & Button Control with ServerClick Event Handler
Programmatically:
Code File:
Default.aspx.cs:
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;
public partial class Default : System.Web.UI.Page
{
HtmlGenericControl span1;
HtmlInputText text1;
HtmlInputButton button1;
HtmlGenericControl span2;
protected void Page_Load(object sender, EventArgs e)
{
this.span1 = new HtmlGenericControl("span");
this.span1.InnerHtml = "<b>Enter Text Here:</b>";
this.span1.Attributes["style"] = "color:green";
this.text1 = new HtmlInputText();
this.text1.Attributes["style"] = "background-color:yellow;color:blue";
this.button1 = new HtmlInputButton();
this.button1.Value = "Submit";
this.button1.Attributes["style"] = "background-color:green;color:white";
this.button1.ServerClick += new EventHandler(button1_Click);
this.span2 = new HtmlGenericControl("span");
this.form1.Controls.Add(this.span1);
this.form1.Controls.Add(this.text1);
this.form1.Controls.Add(this.button1);
this.form1.Controls.Add(this.span2);
}
protected void button1_Click(object sender, EventArgs e)
{
this.span2.InnerHtml = "<br />" + "<b>Your Entered Text: </b>" + this.text1.Value;
}
}

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 60

Output:

ASP.NET Server Controls:


The ASP.NET page framework includes a number of built-in server controls that are designed to provide a
more structured programming model for the Web. ASP.NET Server controls are specifically designed to
work with Web Forms pages.
Web server controls include traditional form controls such as buttons and text boxes as well as complex
controls such as tables. They also include controls that provide commonly used form functionality such as
displaying data in a grid, choosing dates, displaying menus, and so on.
Web server controls offer all of the features described above for HTML server controls (except one-to-one
mapping to elements) and these additional features:

Automatic state management.


A rich object model that provides type-safe programming capabilities.
Automatic browser detection. The controls can detect browser capabilities and render appropriate
markup.
For some controls, the ability to define your own layout for the control using Templates.
For some controls, the ability to specify whether a control's event causes immediate posting to the
server or is instead cached and raised when the page is submitted.
Support for themes, which enable you to define a consistent look for controls throughout your site.
Ability to pass events from a nested control (such as a button in a table) to the container control.
Ability to react to events in server-side code to create applications that are better structured.
Common approach to building user interfaces for Web pages.
Output is automatically customized based on the capabilities of the browser.

Note: Like HTML server controls, Web server controls are also created on the server and they require a
runat="server" attribute to work. However, Web server controls do not necessarily map to any existing
HTML elements and they may represent more complex elements.
The controls use syntax declaratively such as the following:
<TagPrefix:TagName ID=Value runat=Server Attributes />
The attributes in this case are not those of HTML elements. Instead, they are properties of the Web
control.
Example:
<asp:Button id="Button1" runat="server" Text=Button />
When the ASP.NET Web page runs, the Web server control is rendered on the page using appropriate
markup, which often depends not only on the browser type but also on settings that you have made for the
control. For example, a TextBox control might render as an input tag or a textarea tag, depending on its
properties.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 61

ASP.NET includes a large selection of Web server controls that you can use on ASP.NET Web pages,
divided into following categories:

Standard ASP.NET Web Server Controls

Intrinsic Controls (Basic Controls)


o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o

Advanced Controls:
o
o
o
o
o
o

ImageMap
Calendar
AdRotator
View
MultiView
Wizard

Validation Controls:

Label
TextBox
Button
LinkButton
ImageButton
CheckBox
RadioButton
DropDownList
ListBox
CheckBoxList
RadioButtonList
BulletedList
Image
Hyperlink
FileUpload
Literal
HiddenField
PlaceHolder
Panel
Table

RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
ValidationSummary

Navigation Controls:

Menu
TreeView
SiteMapPath

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 62

Data Controls (Data-Bound Controls):

Repeater
DataList
GridView
DetailsView
FormView
ListView

Data Source Controls:

o
o
o

SqlDataSource
ObjectDataSource
AccessDataSource
XmlDataSource
SiteMapDataSource
LinqDataSource
EntityDataSource
DataPager
Chart
QueryExtender

Login Controls:

Login
LoginName
LoginStatus
LoginView
PasswordRecovery
ChangePassword
CreateUserWizard

CrystalReportViewer
ReportViewer

Reporting Controls:

Note:

All ASP.NET Web Server Controls mapped to a corresponding classes found in the
System.Web.UI.WebControls namespace. WebControl is a base class for all ASP.NET Web Server
Controls containing all of the common properties.
The System.Web.UI.WebControls namespace contains classes that allow you to create ASP.NET web
server controls on a Web Forms page. This allows you to programmatically control the ASP.NET Web Server
elements on a Web Forms page.
Control class is an ultimate base class for all ASP.NET Web Server Controls and HTML Server Controls and
all the control classes found in the default assembly of an ASP.NET Web Form Page Framework i.e.
System.Web.dll library assembly.

Creating ASP.NET Web Server Controls Programmatically:


In order to create ASP.NET Web Server Controls programmatically, you need to use the following steps:
Steps:
Step1: Import the corresponding namespace in which all the ASP.NET Web Server Control classes found
i.e. System.Web.UI.WebControls
Step2: Declare the control class object
Step3: Instantiate the control class object
Step4: Set the possible properties values which are required
Step5: Add the event handlers & their event definition if required
Step6: Add the control object to a form container

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 63

For Example: Creating an ASP.NET Label, TextBox & Button Control with Click Event Handler
Programmatically:
Code File:
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
Label label1;
TextBox textbox1;
Button button1;
Label label2;
protected void Page_Load(object sender, EventArgs e)
{
this.label1 = new Label();
this.label1.Text = "Enter Name: ";
this.label1.Font.Bold = true;
this.label1.ForeColor = System.Drawing.Color.Blue;
this.textbox1 = new TextBox();
this.textbox1.BackColor = System.Drawing.Color.Yellow;
this.button1 = new Button();
this.button1.Text = "Submit";
this.button1.Click += new EventHandler(button1_Click);
this.label2 = new Label();
this.form1.Controls.Add(this.label1);
this.form1.Controls.Add(this.textbox1);
this.form1.Controls.Add(this.button1);
this.form1.Controls.Add(this.label2);
}
protected void button1_Click(object sender, EventArgs e)
{
this.label2.Text = "<br />" + "<b>Your Name Is: </b>" + this.textbox1.Text.Trim();
}
}

Output:

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 64

ASP.NET Ajax Server Controls: ASP.NET Ajax server controls that enable you to add Ajax functionality to
an ASP.NET Web page. Ajax functionality includes re-rendering parts of a page with a partial-page update and therefore
avoiding a full-page postback.

ASP.NET AJAX Extension


o

ScriptManager

ScriptManagerProxy

UpdatePanel

UpdateProgress

Timer

Note: All ASP.NET Ajax Server Controls are extension controls to enable Ajax functionality in a web form
mapped

to

corresponding

classes

found

in

the

System.Web.UI

namespace

&

System.Web.Extension.dll library assembly. Control is a base class for all ASP.NET Ajax Server Controls
containing all of the common properties.

User Controls and Custom Controls:


In addition to the built-in controls, the ASP.NET page framework also provides the ability to create user
controls and custom controls. User controls and custom controls can enhance and extend existing controls
to build a much richer user interface.

User Controls:
Often, you may want to reuse the user interface of your Web Form without having to write any extra
code. ASP.NET enables you to do this by converting your Web Forms into user controls. User controls,
which have the .ascx file extension, can be used multiple times within a single Web Form.

Custom Controls:
In addition to the built-in Web controls, ASP.NET also allows you to create your own custom controls.
It may be useful to develop custom controls if you are faced with one of these scenarios:
You need to combine the functionality of two or more built-in Web controls.
You need to extend the functionality of a built-in control.
You need a control that is completely different than any of the controls that currently exist.

Copyright 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 65

You might also like