Web Application Web Forms
Web Application Web Forms
Rakesh Singh
NARESH I TECHNOLOGIES Hyderabad
0
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.
A rich suite of server controls for common tasks, including data access.
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
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.
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 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.
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 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.
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
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 />
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
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:
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:
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.
It supports and enables the same extensibility model and Web.config file settings as IIS 7 and IIS 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.
It does not serve requests to a browser on another computer, making its approval easier in corporate
environments.
Note: Although IIS Express is derived from IIS and supports the core features of IIS, there are some
differences between these servers.
The following table lists typical tasks for IIS Express and how to perform them.
Task
Steps
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.
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.
Windows Version
IIS version
IIS 8.5
IIS 8.0
IIS 7.5
IIS 7.0
IIS 6.0
IIS 5.1
Note: This version of IIS is not recommended; you should use
IIS Express if possible.
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.
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
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>
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
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.
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.
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.
Information
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.
Use this project template to create a website that uses ASP.NET Web Pages with the Razor syntax.
Use this project template to create a website that uses ASP.NET Web Pages version 2 with Razor
syntax.
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.
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.
Project file
structure
Compilation
Namespaces
Deployment
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.
Example: The following code represents a simple page that uses the inline coding model:
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;
}
}
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 />
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
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;
}
}
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;
{
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.
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).
@ 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
@ PreviousPageType
Creates a strongly typed reference to the source page from the target of a crosspage posting.
@ Application
@ Assembly
@ Implements
@ Reference
Links a page, user control, or COM control to the current page or user control
declaratively.
@ OutputCache
@ 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
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.
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.
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
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.
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
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"
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.
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.
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>
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.
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.
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 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
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.
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 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
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_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.
Note: The main purpose of resource files is localization & globalization of the web application.
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
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
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.
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)
{
}
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
OR
protected void Page_LoadComplete (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)
{
}
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:
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)
{
}
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.
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"
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;
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
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
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:
HTML 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.
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:
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:
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
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.
These are following HTML server controls classes that are available in ASP.NET:
Class
Description
HtmlAnchor
HtmlArea
HtmlAudio
HtmlButton
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
HtmlForm
HtmlGenericControl
Defines the methods, properties, and events for all HTML server control elements not
represented by a specific .NET Framework class.
HtmlHead
HtmlIframe
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.
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
HtmlMeta
HtmlSelect
HtmlTable
HtmlTableCell
HtmlTableCellCollection
HtmlTableRow
HtmlTableRowCollection
A collection of HtmlTableRow objects that represent the rows of an HtmlTable control. This
class cannot be inherited.
HtmlTextArea
HtmlTitle
HtmlVideo
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;
}
}
Output:
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.
ASP.NET includes a large selection of Web server controls that you can use on ASP.NET Web pages,
divided into following categories:
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
Repeater
DataList
GridView
DetailsView
FormView
ListView
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.
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:
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.
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:
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.