ASP.
NET
Ms. Amina Raees
ASP.NET - Introduction
ASP.NET is a part of Microsoft .Net platform.
ASP.NET applications are compiled codes, written using
the extensible and reusable components or objects
present in .Net framework.
The ASP.NET application codes can be written in any of
the following languages:
C#
Visual Basic.Net
Jscript
J#
ASP.NET provides three development styles for creating
web applications:
Web Forms
ASP.NET MVC
ASP.NET Web Pages
ASP.NET Web Forms Model
ASP.NET web forms extend the event-driven model of
interaction to the web applications. The browser submits a
web form to the web server and the server returns a
full markup page or HTML page in response.
All client side user activities are forwarded to the server for
stateful processing. The server processes the output of the
client actions and triggers the reactions.
Now, HTTP is a stateless protocol. ASP.NET framework
helps in storing the information regarding the state of the
application, which consists of:
Page state
Session state
ASP.NET life cycle
The ASP.NET life cycle could be divided into two groups:
Application Life Cycle
Page Life Cycle
ASP.NET Application Life Cycle
ASP.NET Application Life Cycle
User makes a request for accessing application resource, a
page. Browser sends this request to the web server.
A unified pipeline receives the first request and the following events
take place:
An object of the class ApplicationManager is created.
An object of the class HostingEnvironment is created to provide
information regarding the resources.
Top level items in the application are compiled.
Response objects are created. The application objects such as
HttpContext, HttpRequest and HttpResponse are created and
initialized.
An instance of the HttpApplication object is created and assigned to
the request.
The request is processed by the HttpApplication class. Different
events are raised by this class for processing the request.
ASP.NET Page Life Cycle
ASP.NET Page Life Cycle
Page Request– This is when the page is first requested from
the server. When the page is requested, the server checks if it
is requested for the first time. If so, then it needs to compile
the page and send it across to the user.
Page Start – During this time, 2 objects, known as the
Request and Response object are created. The Request object
is used to hold all the information which was sent when the
page was requested. The Response object is used to hold the
information which is sent back to the user.
Page Initialization – During this time, all the controls on a
web page is initialized. So if you have any label, textbox or any
other controls on the web form, they are all initialized.
.
Page Load – This is when the page is actually loaded with all
the default values. So if a textbox is supposed to have a default
value, that value is loaded during the page load time.
Validation – Sometimes there can be some validation set on
the form. For example, there can be a validation which says
that a list box should have a certain set of values. If the
condition is false, then there should be an error in loading the
page.
Postback event handling – This event is triggered if the
same page is being loaded again. This happens in
response to an earlier event. Sometimes there can be a
situation that a user clicks on a submit button on the page. In
this case, the same page is displayed again. In such a case, the
Postback event handler is called.
Page Rendering – This happens just before all the
response information is sent to the user. All the
information on the form is saved, and the result is sent to
the user as a complete web page.
Unload – Once the page output is sent to the user,
there is no need to keep the ASP.net web form objects in
memory. So the unloading process involves removing
all unwanted objects from memory.
ASP.NET Page Life Cycle Events
At each stage of the page life cycle, the page raises some events,
which could be coded.
PreInit
Init
InitComplete
LoadViewState
LoadPostData
PreLoad
Load
LoadComplete
PreRender
PreRenderComplete
SaveStateComplete
UnLoad
PreInit - PreInit is the first event in page life cycle. It
checks the IsPostBack property and determines whether
the page is a postback. This event can be handled by
overloading the OnPreInit method or creating a
Page_PreInit handler.
Init - Init event initializes the control property and the
control tree is built. This event can be handled by
overloading the OnInit method or creating a Page_Init
handler.
InitComplete - InitComplete event allows tracking of
view state. All the controls turn on view-state tracking.
LoadViewState - LoadViewState event allows loading
view state information into the controls.
LoadPostData - During this phase, the contents of all
the input fields are defined with the <form> tag are
processed.
PreLoad - PreLoad occurs before the post back data is
loaded in the controls. This event can be handled by
overloading the OnPreLoad method or creating a
Page_PreLoad handler.
Load - The Load event is raised for the page first and
then recursively for all child controls. The controls in the
control tree are created. This event can be handled by
overloading the OnLoad method or creating a Page_Load
handler.
LoadComplete - The loading process is completed, control event
handlers are run, and page validation takes place. This event can be
handled by overloading the OnLoadComplete method or creating a
Page_LoadComplete handler
PreRender - The PreRender event occurs just before the output
is rendered. By handling this event, pages and controls can perform
any updates before the output is rendered.
PreRenderComplete - As the PreRender event is recursively
fired for all child controls, this event ensures the completion of the
pre-rendering phase.
SaveStateComplete - State of control on the page is saved.
Personalization, control state and view state information is saved.
The HTML markup is generated. This stage can be handled by
overriding the Render method or creating a Page_Render handler.
UnLoad - The UnLoad phase is the last phase of the page life cycle.
It raises the UnLoad event for all controls recursively and lastly for
the page itself. Final cleanup is done and all resources and
references, such as database connections, are freed. This event can
be handled by modifying the OnUnLoad method or creating a
Page_UnLoad handler.
ASP.NET Architecture
ASP.NET Web Pages – HTML Forms
Web Forms are web pages built on the ASP.NET Technology.
It executes on the server and generates output to the
browser.
We can use Visual Studio to create ASP.NET Web Forms. It is
an IDE (Integrated Development Environment) that allows us
to drag and drop server controls to the web forms.
It also allows us to set properties, events and methods for the
controls.
To write business logic, we can choose any .NET language like:
Visual Basic or Visual C#.
Web Forms are made up of two components: the visual
portion (the ASPX file), and the code behind the form, which
resides in a separate class file.
Request Object
When a browser asks for a page from a server, it is called
a request. The Request object is used to get information
from a visitor. Its collections, properties, and methods
are described below:
Response Object
The ASP Response object is used to send output to the
user from the server. Its collections, properties, and
methods are described below:
Using ASP.NET Server Side Controls
All web forms are basically instances of the ASP.NET
Page class. The page class has the following extremely
useful properties that correspond to intrinsic objects:
Session
Application
Cache
Request
Response
Server
User
Trace
Server Object
The Server object in Asp.NET is an instance of the
System.Web.HttpServerUtility class. The
HttpServerUtility class provides numerous properties and
methods to perform various jobs.
Request Object
The request object is an instance of the
System.Web.HttpRequest class. It represents the
values and properties of the HTTP request that makes
the page loading into the browser.
Response Object
The Response object represents the server's response to
the client request. It is an instance of the
System.Web.HttpResponse class.
Overview of Control structures
Button Controls
Text Boxes and Labels
Check Boxes and Radio Buttons
List Controls
Drop-down list,
List box,
Radio button list,
Check box list,
Bulleted list.
ListItemCollection
Radio Button list and Check Box list
Bulleted lists and Numbered lists
Image Control
Functions
Creating a Function
ReturnType FunctionName() { }
Calling a Function
<script runat="server">
void Welcome()
{
Response.Write("Welcome to our web site.");
}
</script>
<title>Exercise</title>
</head>
<body>
<%
Welcome();
%>
ASP.NET Web control events
Event Arguments
ASP.NET event handlers generally take two parameters and
return void. The first parameter represents the object raising
the event and the second parameter is event argument.
private void EventName (object sender, EventArgs e);
Application and Session Events
Application_Start - It is raised when the application/website
is started.
Application_End - It is raised when the application/website
is stopped.
Session_Start - It is raised when a user first requests a page
from the application.
Session_End - It is raised when the session ends.
Page and Control Events
DataBinding - It is raised when a control binds to a data
source.
Disposed - It is raised when the page or the control is
released.
Error - It is a page event, occurs when an unhandled
exception is thrown.
Init - It is raised when the page or the control is initialized.
Load - It is raised when the page or a control is loaded.
PreRender - It is raised when the page or the control is to
be rendered.
Unload - It is raised when the page or control is unloaded
from memory.
Event Handling Using Controls
Introduction to web forms
What are web controls ?
Web controls are basically HTML elements wrapped
under easy to use scripting tags of ASP+ and provide rich
functionality in your FORMs or pages.
Web controls range from simple text box to advance
girds and lists.
Some of the controls like data grid can be bound to data
sources much like Visual Basic data bound controls.
What are common web controls available?
Following is a list of common web controls :
Label
Panel
Button
TextBox
CheckBox
RadioButton
RadioButtonList
ListBox
DropDownList
Table/TableRow/TableCell
DataGrid
DataList
Repeater
Calender
Validation controls
How do I handle Web control events?
Web control are processed at server side.
This means that all the events generated by a control will
be handled at server end.
Each event handler now has following syntax :
public sub myeventhandler(source as Object, evt as
EventArgs)
'access your web controls here and
'manipulate their properties
end sub
ASP.NET Server Controls
Server Controls are the tags that are understood by the
server. There are basically three types of server controls.
HTML Server Controls - Traditional HTML tags
Web Server Controls - New ASP. NET tags
Validation Server Controls - For input validation
ASP.NET HTML Server Controls
ASP.NET provides a way to work with HTML Server
controls on the server side programming with a set
of controls collectively is called HTML Controls.
These controls are grouped together in the Visual Studio
Toolbox
HTML elements in ASP. NET files are, by default, treated
as text. To make these elements programmable, add a
runat="server" attribute to the HTML element.
The System.Web.UI.HtmlControls.HtmlControl b
ase class contains all of the common properties. HTML
server controls derive from this class.
ASP.NET Web Server Controls
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.
Mostly all Web Server controls inherit from a common
base class, namely the WebControl class defined in
the System.Web.UI.WebControls namespace.
Validation Controls in ASP.NET
ASP.NET provides several types of validation controls that can be used to validate user input in web forms. Some of the
common validation controls are:
1.RequiredFieldValidation Control
2.CompareValidator Control
3.RangeValidator Control
4.RegularExpressionValidator Control
5.CustomValidator Control
6.ValidationSummary
The below table describes the controls and their use.
All validation controls are rendered in the form of <span> (labels are referred to as <span> on the client by the server)
: Validation Control Description
This control ensures that a field is not left empty or
RequiredFieldValidation blank. It can be used for textboxes, dropdown lists,
checkboxes, and other input controls.
This control compares the value of one input control to
another. It can validate passwords, confirm email
CompareValidator
addresses, and other scenarios where two values must
match.
This control checks if a value falls within a specific
RangeValidator range. For example, it can be used to validate a user's
age, income, or date of birth.
This control checks if a value matches a specified
regular expression pattern. For example, it can validate
RegularExpressionValidator
email addresses, phone numbers, zip codes, and other
input types.
This control allows developers to define their validation
CustomValidator
logic. It usually depends on the business rules.
This control displays a report of all validation errors that
ValidationSummary
occurred on a Web page.
Important points for validation controls
•ControlToValidate property is mandatory for all validate controls.
•One validation control will validate only one input control, but multiple validation control can be assigned to the input
control.
ASP.NET Validation Server Controls
A Validation server control is used to validate the data of
input control. If the data does not pass validation, it will
display an error message to the user.
Validation Controls are derived from a common base
class and share a common set of properties and
methods. You just have to drag and drop the ASP. NET
Validation Control in the web form and write one line of
code to describe its functionality.
This reduces the developer time from writing JavaScript
for each type of validation.
The following code sets the CauseValidation property to true for the submit button on a page:
<asp:Button ID="Button2" runat="server" Text="Submit" CausesValidation=true />
Let's understand validation controls one by one with a practical demonstration:
ASP.NET RequiredFieldValidation Control
The RequiredFieldValidator control is simple validation control that checks to see if the data is
entered for the input control. You can have a RequiredFieldValidator control for each form
element you wish to enforce the mandatory field rule. It has properties
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
Style="top: 98px; left: 367px; position: absolute; height: 26px; width: 162px"
ErrorMessage="password required" ControlToValidate="TextBox2">
</asp:RequiredFieldValidator>
ASP.NET CompareValidator Control
The CompareValidator control allows you to make comparisons to compare data entered in an
input control with a constant value or a value in a different control.
It can most commonly be used when you need to confirm the password entered by the user at
registration time. The data is always case-sensitive.
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Style="top: 145px;
left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password
required" ControlToValidate="TextBox3"></asp:RequiredFieldValidator>
ASP.NET RangeValidator Control
The RangeValidator Server Control is another validator control that checks to see if a control
value is within a valid range. The attributes necessary for this control are MaximumValue,
MinimumValue, and Type.
<asp:RangeValidator ID="RangeValidator1" runat="server"
Style="top: 194px; left: 365px; position: absolute; height: 22px; width: 105px"
ErrorMessage="RangeValidator" ControlToValidate="TextBox4" MaximumValue="100"
MinimumValue="18" Type="Integer"></asp:RangeValidator>
ASP.NET RegularExpressionValidator Control
A regular expression is a powerful pattern matching language that can identify simple and
complex characters' sequences that would otherwise require writing code.
Using RegularExpressionValidator server control, you can check a user's input based on a
pattern you define using a regular expression.
It is used to validate complex expressions. These expressions include a phone number, email
address, zip code, etc. Using a RegularExpressionValidator is very simple. Set the
ValidationExpression property to any expression you want, and it will validate it.
You can create your custom one if you don't find your desired regular expression.
In the example, I have checked the email id format:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Style="top:
234px; left: 366px; position: absolute; height: 22px; width: 177px"
ErrorMessage="RegularExpressionValidator" ControlToValidate="TextBox5"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpression
Validator>
ASP.NET Client Side Control
ASP.NET client side coding has two aspects:
Client side scripts : It runs on the browser and in turn
speeds up the execution of page. For example, client side
data validation which can catch invalid data and warn the
user accordingly without making a round trip to the
server.
Client side source code : ASP.NET pages generate
this. For example, the HTML source code of an ASP.NET
page contains a number of hidden fields and automatically
injected blocks of JavaScript code, which keeps
information like view state or does other jobs to make
the page work.
Client Side Scripts
All ASP.NET server controls allow calling client side code
written using JavaScript or VBScript. Some ASP.NET server
controls use client side scripting to provide response to the
users without posting back to the server. For example, the
validation controls.
Client Side Source Code
ASP.NET pages are generally written in two files:
The content file or the markup file ( .aspx)
The code-behind file
The content file contains the HTML or ASP.NET control
tags and literals to form the structure of the page. The
code behind file contains the class definition. At run-time,
the content file is parsed and transformed into a page
class.
This class, along with the class definition in the code file,
and system generated code, together make the
executable code (assembly) that processes all posted
data, generates response, and sends it back to the client.
Navigation controls
Navigation controls are basically used to navigate the user
through webpage .
There are three controls in ASP.NET ,Which are used
for Navigation on the webpage.
TreeView control
Menu Control
SiteMapPath control
There are some Namespaces, which are used for above
Navigation controls which are given below:
Using.System.Web.UI.WebControls.TreeView ;
Using.System.Web.UI.WebControls.Menu ;
Using.System.Web.UI.WebControls.SiteMapPath ;
Tree View Control
The TreeView control is used for logically displaying the
data in a hierarchical structure.
Tree View Node Editor Dialog Box
Menu Control
The menu control can be used as two types.
Static menu:- It is used to display the parent menu
items and their sub menu items on the page. Means it is
used to display the entire structure of the static menu.
Dynamic menu:- It is used to display the static menu as
well as dynamic menu on the site. It means when user
passes the mouse over the menu then it will appear on
the site.
Static me Step 1: First Add a New Web Form in solution
Explorer -->drag and drop menu control on the
Form-->now select Views = static as shown below:
Dynamic Menu - When user passes the mouse over the
control ,the data will automatically appear on the site.
SiteMapPath Control
It display the current page's context within the entire
structure of a website.
drag and drop SiteMapPath control on the web Form
(SiteMap.aspx)-->Now drag and
drop HyperLink control on the Form as shown below:
Master Page in ASP.NET
Master page allows you to create a consistent look and
behavior for all the pages in your web applications.
Master Page Design is common for all the pages.
Master page actually consists of two pieces,
the master page itself
and one or more content pages.
A master page is an ASP.NET file with the extension
.master.
Advantages of Master Pages
They allow you to centralize the common
functionality of your pages so that you can make
updates in just one place.
They make it easy to create one set of controls and
code and apply the results to a set of pages. For
example, you can use controls on the master page to
create a menu that applies to all pages.
They give you fine-grained control over the layout of the
final page by allowing you to control how the
placeholder controls are rendered.
They provide an object model that allows you to
customize the master page from individual
content pages.
State Management in ASP.NET
Hyper Text Transfer Protocol (HTTP) is a stateless
protocol.
When the client disconnects from the server, the
ASP.NET engine discards the page objects.
This way, each web application can scale up to serve
numerous requests simultaneously without running out of
server memory.
However, there needs to be some technique to store the
information between requests and to retrieve it when
required.
This information i.e., the current value of all the
controls and variables for the current user in the
current session is called the State.
ASP.NET manages four types of states:
View State
Control State
Session State
Application State
View State
The view state is the state of the page and all its controls.
It is automatically maintained across posts by the
ASP.NET framework.
When a page is sent back to the client, the changes in the
properties of the page and its controls are determined,
and stored in the value of a hidden input field named
_VIEWSTATE.
When the page is again posted back, the _VIEWSTATE
field is sent to the server with the HTTP request.
Control State
Control state cannot be modified, accessed directly, or
disabled.
Session State
When a user connects to an ASP.NET website, a new
session object is created.
When session state is turned on, a new session state
object is created for each new request.
This session state object becomes part of the context
and it is available through the page.
The session state object is created from the
HttpSessionState class, which defines a collection of
session state items.
The HttpSessionState class has the following
properties:
Application State
The ASP.NET application is the collection of all web pages,
code and other files within a single virtual directory on a web
server.
When information is stored in application state, it is available
to all the users.
ASP.NET creates an application state object for each
application from the HTTPApplicationState class and stores
this object in server memory.
Application state data is generally maintained by writing
handlers for the events:
Application_Start
Application_End
Application_Error
Session_Start
Session_End
Types of state management in ASP.NET
Client-side State Management
HiddenField Controls
ViewState
Cookies
Control State
QueryString
Server-side State Management
Session
Application
A HiddenField is used to hold values in the client browser. It
can store only one value for a variable and is used in
situations where the value of a variable keeps updating – or
gets updated – regularly.
It cannot be seen, as it is not rendered on the browser. On
every request made to the server, the HiddenField value is
sent like any regular control value.
A cookie is a small text file used to identify users uniquely. It
is located on the client’s computer; it is not stored in the
server’s memory.
There are two types of Cookies:
Persistence Cookies - Cookies that have a specific expiry date
and time are called Persistence cookies.
Non-Persistence Cookies - They maintain information as long
as the user accesses the same browser. Once the browser is
closed, the cookie gets discarded.
Control state –
Users have the option to intentionally disable
the ViewState feature and in such case, if
the ViewState is holding some control information, then
the control’s value could be lost. Because of this, we must
use the ControlState attribute to get the expected
value of the control.
You can use QueryString to store values in the URL.
The value of the query string can be seen in the URL and
is visible to all users.
Server side state management
Session is used to store user information and to
uniquely identify a user (or a browser). ASP.NET uses
a Session ID, which is generated by the server, to keep
track of the status of the current user’s information.
When a new user submits a request to the server,
ASP.NET automatically generates a Session ID and
that Session ID is transmitted with every request and
response made by that particular user.
Application state management is another technique for
maintaining the state on the server-side. The data
persisting in the application state is shared by all users
and that data can be accessed from anywhere within the
application. You can think of this approach
as Application-level state management.